Java – moves an object from a point in a linear path
•
Java
I try to move a sprite in a straight line on the screen towards the position where I touch the screen. What I do is update () in each cycle. It checks the current sprite position xy = = to the destination x, Y. if it has no sprite X and y
Pseudo code of my current sprite object
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++;
Solution
Check out: http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm
This simple algorithm will tell you every x, y coordinate on a line between two points You can use this algorithm to calculate all the locations it needs to access, store the coordinates in the array, and iterate the array when updating the location
From article:
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
This is the original version This article contains a better general algorithm that you should take a look at
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码