How can I move an image from one point to another using Android Canvas

VenkaReddy picture VenkaReddy · Oct 14, 2010 · Viewed 8.1k times · Source

I'm developing a game, and in this game I have to move an image on a Canvas from one point to another in any direction, not just vertical or horizontal.

How can I move that image in this manner?

Answer

Zoe picture Zoe · Oct 5, 2016

After getting a math lecture, it turns out that this is easy to solve. First, we need to get the angle which the target will be moving at.

float deltaX = targetX - startX;
float deltaY = targetY - startY;
float angle = Math.atan2( deltaY, deltaX );

startX/Y can be current X/Y.

Now that we have calculated the angle, we can apply it to the current coordinates:

currentX += speed * Math.cos(angle);//Using cos
currentY += speed * Math.sin(angle);//or sin

to handle the calculations of how much X and Y will be increased by. Using speed as a custom variable if you need to have a custom speed set as well. If you don't need more speed, remove the variable.

And to move the object, apply X/Y to the object:

c.drawBitmap(bm, x, y, null);

Example:

int speed = 10;
int x, y;
int targetX = 100, targetY = 600;
int startX = 900, startY = 100;
public void render(Canvas c){
    super.draw(c);
    float deltaX = targetX - startX;
    float deltaY = targetY - startY;
    float angle = Math.atan2( deltaY, deltaX );
    x += speed * Math.cos(angle);//Using cos
    y += speed * Math.sin(angle);//or sin
    c.drawBitmap(bm, x, y, null);
   (...)
}