1
votes

I have got a sprite that moves based on touch location. I am using box2d for collision and when the sprite collides with another object i rotate the sprite 180 degree to face away from the collision and my aim is to move the sprite that collided x amount of pixels in the direction of rotation basically giving a bounce off affect.

Can anyone tell me how i can get a position which is x amount of pixels in front of the sprite based on the rotation.

Thanks

3

3 Answers

1
votes

You can get the direction your sprite is facing with the following formula:

public static Vector2 AngleToVector(float angle)
{
    return new Vector2((float)Math.Cos(angle), (float)Math.Sin(angle));
}

The vector it returns will be pointing exactly towards the spot you are trying to calculate. Normalize it, then multiply it by the number of pixels you want to reach out to. That should do the trick.

returnedVector = AngleToVector(currentAngle);
returnedVector.Normalize();
returnedVector *= x;

The above is C# code, but you should be able to convert it to your language.

1
votes

You can use the contentSize or boundingBox of the sprite to calculate the amount of pixels you should move. Considering that nodes are anchored in their center, you could do something like this (Changes on the x-axis only):

sprite.position = ccp(sprite.position.x - xAmount - sprite.contentSize.width / 2, sprite.position.y)

Change the signs of the sum according to the orientation you need to move the sprite towards to and the xAmount as you need.

Cheers.

0
votes

You can just convert local point to global:

CGPoint global = [sprite convertoToWorldSpace:ccp(x, 0)];