我写了多边形和圆形测试,其中通过光标,我围绕多边形 360 度旋转,针对中心点 x=0,y=0。
但是,我有一个问题,将多边形居中于鼠标 x,y 而不是边缘。就像现在在屏幕截图中一样,红色圆圈代表当前鼠标位置,绿色是我的目标。
我尝试使用 setOrigin 但这对我来说效果不佳或者我没有正确设置它。 附:忽略白色圆圈。
public class PolygonIntersectsCircle3Test extends AbstractTest {
private Polygon polygon;
private Circle circle;
private boolean collides;
public PolygonIntersectsCircle3Test(Game game) {
super(game);
}
@Override
public void create() {
float width = 300f;
float height = 50f;
polygon = new Polygon(game, Color.WHITE_COLOR, new float[] {
0, 0,
width, 0,
width, height,
0, height
}, 0);
//polygon.setOrigin(width / 2, height / 2);
circle = new Circle(game, Color.WHITE_COLOR, 100, 100, height / 2);
}
@Override
public void update(float deltaTime) {
Vector2 mouseRelativeToScreen = game.getInputController().getMouseRelativeToWorld();
polygon.setPosition(mouseRelativeToScreen.x, mouseRelativeToScreen.y);
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 angleInDegrees(x - circleCenterX, y - circleCenterY);
}
我以前从未使用过 LibGDX,但是 文档 似乎暗示多边形的原点可能打算用作顶点的原点,而不是转换的原点。如果是这样,您应该指定多边形的顶点,就好像它们都被多边形的中心点偏移:
float wd2 = width / 2.0f;
float hd2 = height / 2.0f;
polygon = new Polygon(game, Color.WHITE_COLOR, new float[] {
-wd2, -hd2,
wd2, -hd2,
wd2, hd2,
-wd2, hd2
}, 0);
polygon.setOrigin(0.0f, 0.0f); // I doubt this is necessary, but just in case