I am making a game engine in Java. I am trying to add box collision to my game and this box needs to have the ability to rotate with the player. I have searched and found a formula which is supposed to calculate the new point of a rotated point, however, when I rotate my points they seem to follow a weird out of proportion figure 8 path instead of a circle around the center of my box.
for (Point p : points) {
//Loops through every point on the box (Square)
//top, left, bottom, right
float pointX = p.getX();
float pointY = p.getY();
//rotation as radians
float cos = (float) Math.cos(rotation);
float sin = (float) Math.sin(rotation);
pointX = centerX +(pointX-centerX) * cos + (pointY-centerY) * sin;
pointY = centerY -(pointY-centerY) * cos + (pointX-centerX) * sin;
p.setPos(pointX, pointY);
}
Here is what happens to the box as I rotate my player: https://gyazo.com/ff801ce8458269c2385e24b2dc5404f5
Any help would be greatly appreciated, I have been tackling this for almost a week now with the same results.
The problem is that you calculate pointY
with the new value of pointX
.
Thanks to @Imus answer for the proper calculation.
Try:
float pointX = p.getX();
float pointY = p.getY();
//rotation as radians
float cos = (float) Math.cos(rotation);
float sin = (float) Math.sin(rotation);
float newPointX = centerX +(pointX-centerX) * cos + (pointY-centerY) * sin;
float newPointY = centerY +(pointY-centerY) * cos - (pointX-centerX) * sin;
p.setPos(newPointX, newPointY);