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

后端 未结 2 1782
自闭症患者
自闭症患者 2021-02-13 02:17

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 mo

2条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-13 02:36

    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);
       (...)
    }
    

提交回复
热议问题