简体   繁体   English

将物体以匀速直线从A点移动到B点

[英]Moving an object from point A to point B in a straight line at a constant speed

So essentially what I've been trying to do is to get an object (the player) to fire a bullet in a straight line from it in angle and then just continue on, so if the 'gun' is pointed at an angle of 35 degrees (with 0 degrees being to the right of the screen adding up to 360 going counter-clockwise) then the bullet will travel at a constant speed (say 5) at that angle from the origin.所以基本上我一直在尝试做的是让一个物体(玩家)从它的角度直线发射子弹,然后继续前进,所以如果“枪”指向 35 度角度(屏幕右侧的 0 度加起来为逆时针方向为 360),那么子弹将以恒定速度(例如 5)从原点以该角度行进。

Because the way I've been doing my movement is I've had a function called update that would handle all the drawing and what not.因为我一直在做我的运动的方式是我有一个叫做 update 的函数,它可以处理所有的绘图,什么不是。 Then when it came to movement it would just add a vertical speed and a horizontal speed to the already existing x and y, and it's just been too hard to try to work around it so that it adds a suitable horizontal and vertical speed to move at that angle at a constant speed, so any help will be appreciated.然后当涉及到移动时,它只会为已经存在的 x 和 y 添加一个垂直速度和一个水平速度,而试图解决它实在是太难了,因此它添加了一个合适的水平和垂直速度来移动该角度以恒定速度运行,因此将不胜感激。 -Heath -希思

Maybe you can make your update() method to measure time since it was last invoked, and update location of bullet based on that?也许你可以让你的 update() 方法来测量自上次调用以来的时间,并根据它更新子弹的位置?
It would make bullet to move at approximately constant speed.这将使子弹以近似恒定的速度移动。 (given that FPS is big enough) (鉴于 FPS 足够大)

EDIT2:编辑2:

 public class Bullet { // speed is in units/second // angle is in radians double x; double y; double sv; double sh; public Bullet(double x, double y, double angle, double speed) { this.x = x; this.y = y; sv = Math.sin(angle)*speed; sh = Math.cos(angle)*speed; last_updated = System.currentTimeMillis(); } long last_updated; public void update() { long time_elapsed = System.currentTimeMillis() - last_updated; last_updated = System.currentTimeMillis(); this.x += this.hs*(this.time_elapsed/1000) this.y += this.vs*(this.time_elapsed/1000) } }

Maybe you'll need to play with angle to make it suitable for your coordinate system.也许您需要调整角度以使其适合您的坐标系。 (something like negate the angle, add/substract Pi, and so on.) (例如否定角度、添加/减去 Pi 等。)

Hope this helps.希望这会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM