styphNate
styphNate

Reputation: 156

Make sprite walk along an angle

I am trying to make a sprite walk towards another sprite,

movement_angle = (atan2((y - target->y),(x - target->x)));

if(isWalkable(game,delta))
{
    y -= ((int)(movementspeed)*delta)*sin(((movement_angle)));
    x -= ((int)(movementspeed)*delta)*cos(((movement_angle)));
}

I am calculating the angle and adding the values to my x and y cords. But the movement is not perfect, it does not really follow as I wish, takes weird turns and so on.

Upvotes: 1

Views: 74

Answers (2)

Jonathan Mee
Jonathan Mee

Reputation: 38919

It's hard to say exactly what's going wrong from your code, but here are some things you could look at:

  1. To get a vector from a point to target you'll need to subtract target->x by the point's x and target->y by the point's y
  2. At least movement_angle needs to be a floating point number, though you'll likely want to use doubles for all your 3D geometry values
  3. Why bother with trigonometric functions? You want to walk directly from point x, y to target->x, target->y, why not just use a vector, normalize it, and multiply by your movementspeed and delta?

Upvotes: 3

Gregory Eaton
Gregory Eaton

Reputation: 55

Well you are casting an algebraic result to an int. I think that may be causing your problem.

Upvotes: 0

Related Questions