开发者

Paddle Movement using Box2D

I'm making a game like Arkanoid and to move the ship with mouse, I'm using the following code :

var mousex:int = costume.stage.mouseX;
if (mousex < paddleWidth/2)
    mousex = paddleWidth/2;
else if (mousex > PhysiVals.STAGE_WIDTH - paddleWidth/2)
    mousex = PhysiVals.STAGE_WIDTH - paddleWidth / 2;

var idealLocation:Point = new Point(mousex, ypos);

var directionToTravel:b2Vec2 = new b2Vec2((idealLocation.x -> costume.x) * PhysiVals.paddleSpeed, idealLocation.y-costume.y);

directionToTravel.Multiply(1 / PhysiVals.RATIO);

directionToTravel.Multiply(30);

body.SetLinearVelocity(directionToTravel);

Everything's going fine there! The paddle is moving the way it should! The problem is I want a little inclination towards the direction its moving and when it stops moving the angle of inclination should become zero. I tried playing with the angular velocity but I have no real idea how to开发者_开发问答 do this! So Please help!


The angular velocity of a body is its rotation speed and if I remember correctly Box2D measures it in radians/second. So if you set it to 1 you should see a slow rotation.

body.SetAngularVelocity(1);

(If you don't, it might mean that I'm wrong about the units, or it might mean that you have a constraint on the body preventing it from rotating.)

However it sounds like you want the body to move to a specific angle. There is a function SetXForm which allows you to specify a new position and angle but if you use that then you'll mess with the contact system and Box2D recommends against using this unless an item has genuinely teleported from place to place.

Your paddle isn't doing that, so maybe you could try this.

body.SetAngularVelocity((targetAngle - body.GetAngle()) * x);

x here is a constant which controls the speed of the rotation. Setting it to the clip's FPS will cause the body to snap within a frame to the right angle. Setting it lower will cause a slower, smoother rotation to the required angle, but it will also make the body's rotation more susceptible to influence by contact with other bodies.

The same trick works in order to move the body to a set target location, but it's more verbose:

var delta:b2Vec2 = new b2Vec2(target.x, target.y);
delta.Subtract(body.GetPosition());
delta.Multiply(x);
body.SetLinearVelocity(delta);

It goes without saying that neither of these will work if there's some other static body in the way preventing the motion. Also, by using either of these, you're overwriting the angular/linear velocities Box2D is generating, which means you're going against the grain of the simulation.

caveat: code isn't tested, and was written from memory

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜