简体   繁体   中英

How to make an object move from one point to another via coordinates?

I currently have a 2d game in which I am trying to move a .png image following certain coordinates. If I where to place this object at (0,0) and then try to move to (500,500), I could do the following:

public void move() {
    if (x < 500) {
        x += velocityX;
    }
    if (y < 500) {
        y += velocityY;
    }
}

This would work, but only because its a perfectly diagonal line. With that system, I can only move the object horizontally, vertically, or diagonally, but never in between. If I were to try something like:

public void move() {
    if (x < 500) {
        x += velocityX;
    }
    if (y < 400) {
        y += velocityY;
    }
}

The object would just move in a perfect diagonal angle until it reached 400 on the y axis, it would move horizontally for the last bit to reach 500 on the x axis. How would I make it so that I could move the object to any coordinates while following a straight path?

To move perfect diagonally in your window, you must make sure that the ratio of velocityX and velocityY` should be like this,

 velocityX         width
-----------  =  -----------
 velocityY         height

in Your case if width is 500 , height is 400 and if velocityX is 5, then

 velocityY should be 4

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