我的游戏中有各种实体,它们具有由 vector 数组定义的命中框,
我的一个实体缓慢旋转以跟随玩家的 Action ,所以我自然也需要命中框旋转。
当我将每个顶点绘制到屏幕上时,我的代码会导致线条扭曲。我的实体大小为 64 x 64,因此 + 32 表示对象的中心。
public void rotateVertices(Vector2[] vertices, double angle) {
double cos = Math.cos(angle);
double sin = Math.sin(angle);
for(int i = 0; i < vertices.length; i++){
Vector2 v = vertices[i];
vertices[i].x = ((v.x - (x + 32)) * cos - (v.y - (y + 32)) * sin) + (x + 32);
vertices[i].y = ((v.x - (x + 32)) * sin + (v.y - (y + 32)) * cos) + (y + 32);
}
}
我的构造函数:
public EnemyTriBall(Handler handler, float x, float y) {
super(handler, x, y, 3, 6);
vertices[0] = new Vector2(x + 25, y + 13);
vertices[1] = new Vector2(x + 64, y + 33);
vertices[2] = new Vector2(x + 25, y + 53);
}
最佳答案
这里:
Vector2 v = vertices[i];
您无需复制旧 vector ,只需引用vectices[i]
。所以当你这样做时:
vertices[i].x = ((v.x - (x + 32)) * cos - (v.y - (y + 32)) * sin) + (x + 32);
您修改了原始 vector 的x
。然后在下一行:
vertices[i].y = ((v.x - (x + 32)) * sin + (v.y - (y + 32)) * cos) + (y + 32);
您使用旧的v.y
,但使用新的v.x
,这会给您带来奇怪的结果。最简单的修复方法是获取 x
和 y
并使用它们:
float vx = vertices[i].x;
float vy = vertices[i].y;
vertices[i].x = ((vx - (x + 32)) * cos - (vy - (y + 32)) * sin) + (x + 32);
vertices[i].y = ((vx - (x + 32)) * sin + (vy - (y + 32)) * cos) + (y + 32);
可能还有其他问题,我没有检查公式,但我会从这个开始。
关于java - 为什么我的旋转矩阵不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45927103/