I'm trying to move an object to a new x,y position based on the user's touch location, but I've hit a brick wall.
Currently, I'm coding the movement of the axis manually, but it's producing a scripted, "x then y", resulting in a squared off movement. Ideally, I want to gain a linear path to the touch position, not a square.
My basic movement calculation is here:
//check target not met on x axis
if(spriteX != spriteTargetX){
//check if its left or right
if(spriteTargetX<spriteX){
spriteX -=spriteSpeed;
}else{
spriteX +=spriteSpeed;
}
}
if(spriteY != spriteTargetY){
//check if its up or down
if(spriteTargetY<spriteY){
spriteY -=spriteSpeed;
}else{
spriteY +=spriteSpeed;
}
}
The above algorithm always results in a square movement. I honestly don't know whether I should be performing some kind of distance/angle calculation. Any ideas?
One simple way to do this is to represent the direction of movement as a unit vector, and multiply by the speed. I'll list the basic steps, and give an example where you are at (1,1)
and wish to move to (4,5)
with speed 2
:
diff.x = 3 diff.y = 4
dist = 5 ( sqrt(3^2 + 4^2) = 5 )
diff.x = 0.6 diff.y = 0.8
diff.x = 1.2 diff.y = 1.6
sprite.x = 2.2 sprite.y = 2.6