Reputation: 97
I have various entities in my game that have hit-boxes defined by Vector array's,
one of my entities rotates slowly to follow the player's movements so naturally I need the hit-box to rotate too.
My code results in warped and distorted lines as I draw each vertex to the screen. My entites are 64 x 64 in size so + 32 indicates the center of the object.
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);
}
}
my constructor:
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);
}
Upvotes: 1
Views: 495
Reputation: 43709
Here:
Vector2 v = vertices[i];
You don't make a copy of the old vector, you just reference vectices[i]
. So when you do this:
vertices[i].x = ((v.x - (x + 32)) * cos - (v.y - (y + 32)) * sin) + (x + 32);
you modify x
of of the original vector. Then in the next line:
vertices[i].y = ((v.x - (x + 32)) * sin + (v.y - (y + 32)) * cos) + (y + 32);
You use old v.y
but new v.x
which gives you weird results. The easiest fix would be to get x
and y
and use them instead:
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);
There might be other issues, I did not check the formulas but I'd start with this one.
Upvotes: 1