在线性路径中将对象从一个点移动到另一个点

Shi*_*u18 6 java algorithm pathing coordinates game-physics

我试图在屏幕上直线移动一个精灵,朝着我触摸屏幕的位置,我做的是在每个循环中更新(),它检查当前精灵的位置xy = =到目的地x,y.如果它没有精灵的x ++和y ++ ......那就是..它不是直线移动...因为有些情况下x或y坐标首先到达目的地x或y ...如何我是否改变它以使x和y一起与目的地相遇?

我目前的精灵对象的伪代码

             destX = destination X
             destY = destination Y

             posX = current X
             posY = current Y
               public void update(){
                if(destX > posX && destY < posY)
                {

                    posX++;
                    posY--;
                }
                else if (destX > posX && destY > posY){
                    posX++;
                    posY++;
                }
                else if(destX < posX && destY > posY)
                {
                    posX--;
                    posY++;
                }
                else if(destX < posX && destY < posY){
                    posX--;
                    posY--;
                }
                else if(destX < posX)
                    posX--;
                else if(destX > posX)
                    posX++;
                else if(destY < posY)
                    posY--;
                else if(destY > posY)
                    posY++;
Run Code Online (Sandbox Code Playgroud)

Jos*_*osh 5

查看:http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm

这个简单的算法将告诉你两点之间的一条线上的每个X,Y坐标.您可以使用此算法计算它需要访问的所有位置,将坐标存储在数组中,并在更新位置时迭代数组.

来自文章:

  function line(x0, x1, y0, y1)
         int deltax := x1 - x0
         int deltay := y1 - y0
         real error := 0
         real deltaerr := abs (deltay / deltax)    // Assume deltax != 0 (line is not vertical),
               // note that this division needs to be done in a way that preserves the fractional part
         int y := y0
         for x from x0 to x1
             plot(x,y)
             error := error + deltaerr
             if error ? 0.5 then
                 y := y + 1
                 error := error - 1.0
Run Code Online (Sandbox Code Playgroud)

这是最原始的版本.本文包含一个更好的通用算法,您应该看一下.