Android:如何根据目标的坐标旋转移动的动画精灵
问题描述:
我的应用程序在Canvas周围启动精灵实例,然后在屏幕上向x/y坐标移动。我希望能够围绕其中心旋转精灵,使其面向目标坐标。我正在使用精灵表,并且遇到剪辑问题。我也找到了很多很好的例子,但是没有任何东西可以覆盖我正在寻找的东西。 This example is very close但为了提高效率,我正在使用ImagePooler类,无法在每次绘制/旋转时重新加载图像。所以,如果有人想知道如何旋转预加载的图像来切割我的精灵表,我将非常感激。Android:如何根据目标的坐标旋转移动的动画精灵
答
首先,它很容易旋转,你可以用帆布或矩阵精灵:
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一样的常量,这取决于你的精灵初始点的位置。
我不知道这是否会工作,但希望它可以给你一些想法...
答
使用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);
}
我的精灵每个人都有自己的绘画方法,我用一个矩形对象拉出精灵表我想画的一部分,所以矩阵的选择似乎是出questio的ñ(虽然由于某种原因,我认为这是我更喜欢的选择)。但是,Canvas方法正在(几乎)正如我所希望的那样工作,并对你的spriteToDestAngle代码进行了一些调整,我将找到所需的东西。 – bwags 2011-05-14 23:56:13
很高兴有用:) – Lumis 2011-05-16 10:00:38