Android: How to rotate a moving animated sprite based on the coordinates of its destination

前端 未结 2 738
感动是毒
感动是毒 2020-12-14 05:11

My application fires up sprite instances around a Canvas which then move across the screen towards a x/y coordinate. I would like to be able to rotate the sprite around its

相关标签:
2条回答
  • 2020-12-14 05:21

    First it is easy to rotate a sprite you can use canvas or matrix:

    Matrix matrix = new Matrix();
    matrix.postRotate(angle, (ballW / 2), (ballH / 2)); //rotate it
    matrix.postTranslate(X, Y); //move it into x, y position
    canvas.drawBitmap(ball, matrix, null); //draw the ball with the applied matrix
    
    // method two 
    canvas.save(); //save the position of the canvas
    canvas.rotate(angle, X + (ballW / 2), Y + (ballH / 2)); //rotate the canvas' matrix
    canvas.drawBitmap(ball, X, Y, null); //draw the ball on the "rotated" canvas
    canvas.restore(); //rotate the canvas' matrix back
    //in the second method only the ball was roteded not the entire canvas
    

    To turn it towards a destination you need to know the angle between the sprite and the destination:

    spriteToDestAngle =  Math.toDegrees(Math.atan2((spriteX - destX)/(spriteY - destY)));
    

    Now all you need to do is to use this angle for the sprite rotation plus ajust it with a constant like angleShift which depends to where your sprite initially points.

    I am not sure if this will work but hope it may give you some ideas...

    0 讨论(0)
  • 2020-12-14 05:42

    using this referance to calculate Angle:

    private double angleFromCoordinate(double lat1, double long1, double lat2,
            double long2) {
    
        double dLon = (long2 - long1);
    
        double y = Math.sin(dLon) * Math.cos(lat2);
        double x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1)
                * Math.cos(lat2) * Math.cos(dLon);
    
        double brng = Math.atan2(y, x);
    
        brng = Math.toDegrees(brng);
        brng = (brng + 360) % 360;
        brng = 360 - brng;
    
        return brng;
    }
    

    and then rotate ImageView to this angle

    private void rotateImage(ImageView imageView, double angle) {
    
        Matrix matrix = new Matrix();
        imageView.setScaleType(ScaleType.MATRIX); // required
        matrix.postRotate((float) angle, imageView.getDrawable().getBounds()
                .width() / 2, imageView.getDrawable().getBounds().height() / 2);
        imageView.setImageMatrix(matrix);
    }
    
    0 讨论(0)
提交回复
热议问题