【问题标题】:Android: How to rotate a moving animated sprite based on the coordinates of its destinationAndroid:如何根据目的地坐标旋转移动的动画精灵
【发布时间】:2011-08-25 14:51:45
【问题描述】:

我的应用程序在 Canvas 周围启动 sprite 实例,然后在屏幕上朝 x/y 坐标移动。我希望能够围绕其中心旋转精灵,使其面向目标坐标。我正在使用精灵表并且遇到了剪辑问题。我还找到了很多很好的例子,但似乎没有什么能完全涵盖我正在寻找的内容。 This example is very close 但为了提高效率,我使用的是 ImagePooler 类,并且无法在每次绘制/旋转时重新加载图像。因此,如果有人知道如何在不切割我的精灵表的情况下旋转预加载的图像,我将不胜感激。

【问题讨论】:

    标签: android image-rotation sprite-sheet


    【解决方案1】:

    首先,旋转一个可以使用画布或矩阵的精灵很容易:

    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
    

    要将其转向目的地,您需要知道精灵与目的地之间的角度:

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

    现在你需要做的就是使用这个角度来进行精灵旋转,并用一个像angleShift这样的常数来调整它,这取决于你的精灵最初指向的位置。

    我不确定这是否可行,但希望它能给你一些想法......

    【讨论】:

    • 我的每个精灵都有自己的绘制方法,我使用 Rectangle 对象拉出我想要绘制的精灵表部分,因此矩阵选项似乎是不可能的(尽管出于某种原因,我认为这是我更喜欢的选择)。然而,Canvas 方法的工作(几乎)完全符合我的期望,只要稍微调整一下你的 spriteToDestAngle 代码,我就会得到我想要的。
    【解决方案2】:

    使用this引用计算角度:

    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;
    }
    

    然后将ImageView旋转到这个角度

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-13
      • 1970-01-01
      • 2015-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多