Search code examples
androidopengl-espath-findingopengl-es-1.1

Moving object to touch x y


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?


Solution

  • 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:


    • Get difference between destination and current. (diff.x and diff.y)
    diff.x = 3
    diff.y = 4
    
    • Get the total distance from destination to current.
    dist = 5 ( sqrt(3^2 + 4^2) = 5 )
    
    • Divide diff.x and diff.y by the distance
    diff.x = 0.6  
    diff.y = 0.8
    
    • Multiply diff.x and diff.y by desired speed
    diff.x = 1.2 
    diff.y = 1.6
    
    • Add diff.x and diff.y to sprite's x and y, respectively
    sprite.x = 2.2
    sprite.y = 2.6