0
votes

What I'm trying to achieve is a sprite moving to another sprite in a 2D environment. I started with the basic Mx = Ax - Bx deal. But I noticed that the closer to the target the sprite gets, the more it slows down. So I tried to create a percentage/ratio based on the velocity then each x and y gets their percent of a speed allowance, however, it's acting very strangely and only seems to work if Mx and My are positive Here's the code extract:

ballX = ball->GetX();
    ballY = ball->GetY();
    targX = target->GetX();
    targY = target->GetY();
    ballVx = (targX - ballX);
    ballVy = (targY - ballY);
    percentComp = (100 / (ballVx + ballVy));
    ballVx = (ballVx * percentComp)/10000;
    ballVy = (ballVy * percentComp)/10000;

The /10000 is to slow the sprites movement

2
You could use pythagorean theorem to set the length of ballV to a specific number. - Guillaume Racicot
"I started with the basic Mx = Ax - Bx deal. But I noticed that the closer to the target the sprite gets, the more it slows down." Sounds like something was wrong with your inputs or outputs in the first place You need to debug that not adjust the formula to account for your mistake. You should be finding the vector to the second point and scaling that vector by the delta time to find the new position. - Jonathan Mee

2 Answers

1
votes

Assuming you want the sprite to move at a constant speed, you can do a linear fade on both the X and Y position, like this:

#include <stdio.h>

int main(int, char **)
{
   float startX = 10.0f, startY = 20.0f;
   float endX = 35.0f, endY = -2.5f;
   int numSteps = 20;

   for (int i=0; i<numSteps; i++)
   {
      float percentDone = ((float)i)/(numSteps-1);
      float curX = (startX*(1.0f-percentDone)) + (endX*percentDone);
      float curY = (startY*(1.0f-percentDone)) + (endY*percentDone);

      printf("Step %i:  percentDone=%f curX=%f curY=%f\n", i, percentDone, curX, curY);
   }
   return 0;
}
0
votes

Thanks for the responses, I got it working now but normalising the vectors instead of the whole percent thing, here's what I have now:

    ballX = ball->GetX();
    ballY = ball->GetY();
    targX = target->GetX();
    targY = target->GetY();
    ballVx = (targX - ballX);
    ballVy = (targY - ballY);
    vectLength = sqrt((ballVx*ballVx) + (ballVy*ballVy));
    ballVx = (ballVx / vectLength)/10;
    ballVy = (ballVy / vectLength)/10;