如何实现Polygon以鼠标坐标(x,y)为中心而非边缘?(附测试代码)
解决方案
要让Polygon以鼠标坐标为中心对齐并围绕(0,0)旋转,你需要调整原点设置和位置计算逻辑,具体步骤如下:
- 启用Polygon的中心原点:取消
create方法中setOrigin的注释,将旋转中心设为Polygon的几何中心。
- 启用Polygon的中心原点:取消
- 修正位置偏移:因为LibGDX中
Polygon.setPosition()设置的是其顶点起始点((0,0))的坐标,所以要让中心对齐鼠标,需要用鼠标坐标减去Polygon的半宽和半高,把起始点偏移到正确位置。
- 修正位置偏移:因为LibGDX中
修改后的完整代码如下:
public class PolygonIntersectsCircle3Test extends AbstractTest { private Polygon polygon; private Circle circle; private boolean collides; // 存储Polygon尺寸,方便后续计算 private float polygonWidth; private float polygonHeight; public PolygonIntersectsCircle3Test(Game game) { super(game); } @Override public void create() { polygonWidth = 300f; polygonHeight = 50f; polygon = new Polygon(game, Color.WHITE_COLOR, new float[] { 0, 0, polygonWidth, 0, polygonWidth, polygonHeight, 0, polygonHeight }, 0); // 设置旋转原点为Polygon几何中心 polygon.setOrigin(polygonWidth / 2, polygonHeight / 2); circle = new Circle(game, Color.WHITE_COLOR, 100, 100, polygonHeight / 2); } @Override public void update(float deltaTime) { Vector2 mouseRelativeToScreen = game.getInputController().getMouseRelativeToWorld(); // 计算偏移后的位置,让Polygon中心对齐鼠标坐标 float posX = mouseRelativeToScreen.x - polygonWidth / 2; float posY = mouseRelativeToScreen.y - polygonHeight / 2; polygon.setPosition(posX, posY); float degrees = degrees(mouseRelativeToScreen.x, mouseRelativeToScreen.y, 0, 0); polygon.setRotation(degrees); collides = polygon.contains(circle.x, circle.y); } @Override public void draw() { game.getShapeRenderer().begin(ShapeRenderer.ShapeType.Line); if (collides) { game.getShapeRenderer().setColor(Color.RED); } else { game.getShapeRenderer().setColor(Color.WHITE_COLOR); } game.getShapeRenderer().polygon(polygon.getTransformedVertices()); game.getShapeRenderer().circle(circle.x, circle.y, circle.radius); game.getShapeRenderer().end(); } } public static strictfp float degrees(float x, float y) { float degrees = (float) StrictMath.toDegrees(StrictMath.atan2(y, x)); if (degrees < -360.0f || degrees > 360.0f) { degrees %= 360.0f; } if (degrees < 0.0f) { degrees += 360.0f; } return degrees; } public static strictfp float degrees(float x, float y, float circleCenterX, float circleCenterY) { return degrees(x - circleCenterX, y - circleCenterY); }
关键说明
- 原点设置:
setOrigin(polygonWidth/2, polygonHeight/2)让Polygon围绕自身几何中心旋转,这是实现中心对齐的基础。 - 位置修正:默认情况下
setPosition()会把Polygon的(0,0)顶点放在目标坐标,所以减去半宽半高后,Polygon的中心会刚好落在鼠标位置。 - 旋转逻辑保持不变:你之前计算的角度是鼠标相对于(0,0)的夹角,完全符合“围绕(0,0)旋转”的需求。
内容的提问来源于stack exchange,提问作者Kapparino
相关产品推荐
相关产品推荐

