1
votes

I haven't been able to find this after scavenging the forums. I would like to implement something like this ... the main character always moves in the direction it's facing. When the player touches the screen, the character will turn to face that touch location, which should cause the body to move in a different direction.

I can get the character to face a touch location as follows:

CGPoint diff = ccpSub(location, self.position);
CGFloat targetAngle = atan2f(diff.y, diff.x);
self.body->a = targetAngle;

I want something along these lines. Get the current angle the character is facing. Turn that angle into a unit vector. Multiply that unit vector by a max_velocity, and apply it to the character. This should should (theoretically) move the character in the direction it is facing at a constant velocity?

This seems to give me what I want:

cpVect rotatedVel = cpvmult(ccpForAngle(self.body->a), MAX_VELOCITY);
self.body->v = cpvlerpconst(self.body->v, rotatedVel, ACCELERATION * dt);

Now all I need is a way to rotate the character's direction slowly over time. How might I do that?

2

2 Answers

0
votes

Sounds like you want to do something like this from Chipmunk's Tank demo:

// turn the control body based on the angle relative to the actual body
cpVect mouseDelta = cpvsub(ChipmunkDemoMouse, cpBodyGetPos(tankBody));
cpFloat turn = cpvtoangle(cpvunrotate(cpBodyGetRot(tankBody), mouseDelta));
cpBodySetAngle(tankControlBody, cpBodyGetAngle(tankBody) - turn);

'turn' is calculated relative to the body's current rotation by transforming the direction vector relative to the body's current rotation. The demo smooths out the rotation using constraints (which you might want to consider here too), but you could also just get away with using cpflerpconst() on 'turn' to get a maximum angular velocity too.

0
votes

What about using the cpBodySetTorque to set object torque to make it spin/rotate?