我正在制作一款涉及用户点击方向拍摄的游戏。
所以从点A(x,y)到点B(x1,y1)我希望子弹位图有动画,我已经完成了一些计算/数学,并想出了一些方法来做到这一点,但它是不是那么好看并不自然。
我这样做的方法是计算x和x1,y和y1之间的差异,然后缩放它。
例如,如果x和x1之间的X差为100且y和y1之间的Y差异,我计算X / Y并得到2.0等于2:1,所以我知道我应该比Y快两倍。
这是我的代码,如果有人有任何建议如何让它变得更好,请告诉我。
float proportion;
float diffX = (x1 - x);
if(diffX == 0) diffX = 0.00001f;
float diffY = (y1 - y);
if(diffY == 0) diffY = 0.00001f;
if(Math.abs(diffX)>Math.abs(diffY)){
proportion = Math.abs(diffX)/Math.abs(diffY);
speedY = 2;
speedX = proportion * speedY;
}
else if(Math.abs(diffX)<Math.abs(diffY)){
proportion = Math.abs(diffY)/Math.abs(diffX);
speedX = 2;
speedY = proportion * speedX;
}
else{
speedX = speedY = 2;
}
if(diffY<0) speedY = -speedY;
if(diffX<0) speedX = -speedX;
if(speedX>=10) speedX = 9;
if(speedX<=-10) speedX = -9;
if(speedY>=10) speedY = 9;
if(speedY<=-10) speedY = -10;
答案 0 :(得分:1)
以下实现LERP(线性插值)以使您沿直线移动。
// move from (x1, y1) to (x2,y2) with speed "speed" (that must be positive)
final double deltay = y2-y1;
final double deltax = x2-x1;
double deltalen = sqrt(deltay*deltay + deltax*deltax);
if (deltalen <= speed)
display(x2, y2);
else {
double finalx = x1 + deltax * speed/deltalen; // surely deltalen > 0, since speed >=0
double finaly = y1 + deltay * speed/deltalen;
display(finalx, finaly);
}
答案 1 :(得分:0)
以下是详细说明我的评论的代码:
float slope = (x2 -x1)/(y2 - y1);
float dx = 0.1f; // tweake to set bullet's speed
float x = x1;
while(x < x2)
{
float y = slope*(x - x1) + y1;
DisplayBullet(x, y);
x += dx;
}
// at this point x = x2 and, if everything went right, y = y2
这里我假设x1 < x2
。如果不是这种情况,你将不得不交换积分。