我想要实现的是在2D环境中移动到另一个精灵的精灵。我从基本的Mx = Ax - Bx交易开始。但是我注意到精灵越接近目标,它就越慢。因此,我尝试根据速度创建一个百分比/比率,然后每个x和y得到它们的速度限制的百分比,然而,它的行为非常奇怪,只有当Mx和My为正时才会起作用 这是代码提取:
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;
/ 10000是为了减慢精灵运动
答案 0 :(得分:1)
假设您希望精灵以恒定速度移动,您可以在X和Y位置进行线性渐变,如下所示:
#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;
}
答案 1 :(得分:0)
感谢您的回复,我现在已经开始工作,但正常化向量而不是整个百分比,这就是我现在所拥有的:
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;