views:

151

answers:

1

I've got some jerky movement of my sprite.

Basically, when the user touches a point on the screen, the sprite should move to that point. This is working mostly fine... it's even taking into account a delta - because frame rate may not be consistant.

However, I notice that the y movement usually finishes before the x movement (even when the distances to travel are the same), so it appears like the sprite is moving in an 'L' shape rather than a smooth diagonal line.

Vertical and horizontal velocity (vx, vy) are both set to 300. Any ideas what's wrong? How can I go about getting my sprite to move in a smooth diagonal line?

 - (void)update:(ccTime)dt
{
int x = self.position.x;
int y = self.position.y;

    //if ball is to the left of target point
if (x<targetx)
{
            //if movement of the ball won't take it to it's target position
    if (x+(vx *dt) < targetx)
    {
        x += vx * dt;
    }
    else {
        x = targetx;
    }

} else if (x>targetx) //same with x being too far to the right
{
    if (x-(vx *dt) > targetx)
    {
        x -= vx * dt;
    }
    else {
        x = targetx;
    }

}
if (y<targety)
{
    if (y+(vy*dt)<targety)
    {
        y += vy * dt;
    }
    else {
        y = targety;
    }

} else if (y>targety)
{
    if (y-(vy*dt)>targety)
    {
        y -= vy * dt;
    }
    else {
        y = targety;
    }

}
self.position = ccp(x,y);
}
+1  A: 

You want to move to (targetx, targety) from any (x,y) and arrive at both coordinates at the same time (to avoid the "dogleg"). So, suppose the x velocity is vx and you get there in t seconds. That means vx = (targetx - x)/t. t must be the same for the y coordinate if you want smooth movement to the same point at the same time, so that means t = (targetx - x)/vx and vy must actually be (targety - y)*vx/(targetx - x).

In other words, you can't set vx and vy separately and get the result you want.

Jim
I think I get this, so x += vx * dt; and y += (targety - y)*vx/(targetx - x) *dt ?
mac_55
Yes, but watch out for dividing by zero if (targetx - x) = 0.
Jim