简体   繁体   中英

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.

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. 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. -Heath

Maybe you can make your update() method to measure time since it was last invoked, and update location of bullet based on that?
It would make bullet to move at approximately constant speed. (given that FPS is big enough)

EDIT2:

 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.)

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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