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?
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.
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).
Displays image resources, for example Bitmap or Drawable resources. ImageView is also commonly used to apply tints to an image and handle image scaling.
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);
(...)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With