Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 744
VenkaReddy Avatar asked Oct 14 '10 05:10

VenkaReddy


People also ask

How do I move a bitmap in Canvas?

you can use your finger to drag and on release bitmap is drawn to that place. Instead of image view on click draw a image on to the canvas. check the edit. main.

What is onDraw in android?

The parameter to onDraw() is a Canvas object that the view can use to draw itself. The Canvas class defines methods for drawing text, lines, bitmaps, and many other graphics primitives. You can use these methods in onDraw() to create your custom user interface (UI).

What is ImageView in android?

Displays image resources, for example Bitmap or Drawable resources. ImageView is also commonly used to apply tints to an image and handle image scaling.


1 Answers

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);
   (...)
}
like image 53
Zoe stands with Ukraine Avatar answered Oct 04 '22 10:10

Zoe stands with Ukraine