I'm experimenting with a breakout-style game. I've found a nice collision handler function for another library which makes the ball bounce off of the paddle at an angle based on the position of where the ball hit the paddle (this isn't realistic physics but it's the typical breakout-style physics). E.g. if the ball hits the center of the paddle, it simply bounces off at the same angle, and if it hits close to the edges of the paddle it could either increase or decrease its angle, based on its own angle and whether the ball hit the left portion or right portion of the paddle.
Quoting from the forum post from here:
Here's a good physics setup for your ball's collision handler:
Code: Select all
protected function handleContact(e:ContactEvent):void
{
//don't handle contacts that aren't with the paddle
if (!(e.other.GetBody().GetUserData() is Paddle) || !live)
return;
//get a reference to the paddle
var paddle:Paddle = e.other.GetBody().GetUserData() as Paddle;
//only change collisions that are against the top surface of the paddle (let it shank off if it hits an edge).
var collisionNormal:V2 = e.getWorldManifold().normal;
if(collisionNormal.x == 0 && collisionNormal.y == 1)
{
var diff:Number = x - paddle.x; //x distance between ball and paddle.
var ratio:Number = diff / (paddle.width / 2); //distance as a ratio (between -1 and 1)
if (ratio < -1 || ratio > 1) //it will shank.
return;
//Create a new velocity vector and set it to the ball's current speed.
var velocity:V2 = _body.GetLinearVelocity();
var speed:Number = velocity.length();
//set the ball to be going straight up at the same speed as it came.
velocity = new V2(0, -1);
velocity.normalize(speed);
//rotate the velocity angle between a specific range (I chose 1 radian) as a proportion ball's distance from center of paddle.
velocity.rotate(paddleBounceAngleRange * ratio);
_body.SetLinearVelocity(velocity);
}
}
So far I know how to:
- Set a collision handler that is only called when a ball hits a paddle (via cpSpaceAddCollisionHandler and collision types)
- I'm using a beginCollision callback, I assume this is where I'm supposed to manipulate the velocity/angle of the ball.
But this is where I fall short, the original code checks the normals to be (0, 1), but my normals returned from the cpArbiterGetContactPointSet call are almost always (0, -1). And I'm not sure how to translate the rest of the code, such as the usage of GetLinearVelocity and paddleBounceAngleRange.
Does someone know how to implement a simple C handler based on the Citrus one?
Cheers.