Basically there is an accelerometer handler that moves a round object. The movement speed depends on the tilt of the device.
If this object collides with an object that sub-classes the "border" class, it halts.
I've encountered a trembling effect that happens when the collisions angle is near vertical \ near horizontal (i.e. if our object collides with a horizontal border, it starts trembling).
Also, there is a trembling effect when our object collides with a vertical and horizontal border at the same time.
so, here is the original code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| var angle:Number = collisionArray[collisionIndex].angle; // Get The Collision Angle. var overlap:int = collisionArray[collisionIndex].overlapping.length; var sin:Number = Math.sin(angle); var cos:Number = Math.cos(angle); var vx:Number = OurObject.accelX; // Gets acceleration from the accelerometer handlervar vy:Number = OurObject.accelY; var vx0:Number = vx * cos + vy * sin; var vy0:Number = vy * cos - vx * sin; vx = vx0 * cos - vy0 * sin; vy = vy0 * cos + vx0 * sin; vx -= cos * overlap / OurObject.getRadius(); vy -= sin * overlap / OurObject.getRadius(); OurObject.x += vx; OurObject.y += vy; |
As you see, we check the collision's angle and overlap, from a collisions array I've defined earlier (using the CollisionGroup.checkCollisions() method).
The X\Y velocities come from the accelerometer handler.
By those parameters, our object knows how much to move in order to not overlap the border, thus not crossing it.
But there is a trembling effect when the angle is nearly vertical\horizontal. This happens because of the sin\cos values in these angles.
In order to fix this problem, I've inserted the following code after line 4:
1
2
3
4
5
6
7
8
9
10
11
12
13
| /// Start of Tremble Prevention. if (Math.abs(sin) > 0.9) { // if ball hits a nearly horizontal border. sin = Math.abs(sin)/sin * 0.5; } else if (Math.abs(cos) > 0.9) { // if ball hits a nearly vertical border. cos = Math.abs(cos)/cos * 0.5; } else if (Math.abs(Math.abs(cos) - Math.abs(sin)) > 0.05){ // if ball hits two borders that have a near 90 degree angle between them. /// NOTE! Sin and Cos values cannot be 0 together, so no conflict will happen. sin = Math.abs(sin)/sin * 0.5; cos = Math.abs(cos)/cos * 0.5; } /// End of Tremble Prevention. |
Basically, the Math.Abs() Method is there because the collision can happen from both sides of the border.
That's It! Hope it helped anybody.
No comments:
Post a Comment