java – 在线性路径中从一个点移动一个对象

我试图在屏幕上直线移动一个精灵,朝着我触摸屏幕的位置,我做的是在每个循环中更新(),它检查当前精灵的位置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++;

解决方法

退房: 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

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

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...