【发布时间】:2018-12-22 01:39:10
【问题描述】:
我正在编写游戏代码,并且希望每帧每隔一段时间,弹丸就会从一个位置移动到下一个位置。
我一直在玩确定事物的斜率截距方法,并且我正在接近,但我被卡住了。
到目前为止,这是我的代码:
animationFrame = refresh;
double x, y, xPerF; //Values for drawing
double m, b; //Value for slope and y-intercept
double x1, x2, y1, y2; //Values for the targets
x1 = getCenterX();
x2 = Canvas.target[shotTarget].getCenterX();
y1 = getCenterY();
y2 = Canvas.target[shotTarget].getCenterY();
xPerF = Point2D.distance(x1, y1, x2, y2)/animationSpeed;
//Calculate slope
if(x2>x1) m = (y2-y1)/(x2-x1);
else if(x2<x1) m = (y1-y2)/(x1-x2);
else m = 0;
//Calculate the y-intercept
b = m * x1 - y1;
if(b<0) b = -b + Canvas.myHeight;
else {
b -= Canvas.myHeight;
if(b<0) b = -b;
}
//Calculate the x value
if(x1>x2) x = x1 - (xPerF * animationFrame);
else if(x1<x2) x = x1 + (xPerF * animationFrame);
else x = x1;
//Calculate the y value
if(m!=0) y = (m * x + b) - Canvas.myHeight;
else {
if(y1>y2) y = y1 - (xPerF * animationFrame);
else y = y1 + (xPerF * animationFrame);
}
g.fillOval((int) x - 15, (int) y - 15, 30, 30);
//Debugging
System.out.println("Frame " + animationFrame + " of " + animationSpeed + " | " + y + " = " + m + " * " + x + " + " + b + " | at speed of " + xPerF);
更新
我希望动画在目标位置结束,但它总是过冲或正好在目标上。当目标在塔的正上方时,它主要是过冲,给或取几个 x 坐标。我已经把它计算为一个象限 1 x-y 平面,我相信我现在遇到的问题在于我如何计算我的斜率。谢谢!
过时的
这里有一个小程序来演示:https://drive.google.com/file/d/1fCTFJzulY1fcBUmdV6AXOd7Ol1g9B3lo/view?usp=sharing
点击每个目标来定位它
【问题讨论】:
-
也许你可以准备可重现的例子?
-
@Antoniossss 你什么意思?
-
我的意思是创建一段我可以在本地实际运行的代码,也许可以尝试修复它。
-
为什么要重新发明轮子?查看物理引擎,例如 box2d。
-
我想复制粘贴然后运行看看效果。