سؤال

I'm doing a couple of tests with polygons (rotating them) and I've run into an annoying issue that crops up while I'm rotating them. The issue is, the polygons seem to be moving when they rotate, and eventually they fly out of the screen. I've been using AffineTransform to rotate them, and I haven't been translating them so they shouldn't be moving, right? Here's the code:

import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;

public class PhysicsProp {
    Point2D[] OriginalPoints;
    Point2D[] NewPoints = OriginalPoints;

    int X;
    int Y;

    double rotation = 0.0;

    public PhysicsProp(Point2D[] Points){
        OriginalPoints = Points;
        NewPoints = Points;
    }

    public Polygon PointsToPoly(Point2D[] Points){
        Polygon p = new Polygon();
        for (int i = 0; i < Points.length; i++){
            p.addPoint((int) Points[i].getX(), (int) Points[i].getY());
        }
        return p;
    }

    public void rotateModel(double theta){
        AffineTransform.getRotateInstance(Math.toDegrees(theta), PointsToPoly(NewPoints).getBounds().getCenterX(), PointsToPoly(NewPoints).getBounds().getCenterY()).transform(OriginalPoints, 0, NewPoints, 0, OriginalPoints.length);
    }

    public Polygon getModel(){
        return PointsToPoly(NewPoints);
    }

    public void setModel(Point[] points){
        OriginalPoints = points;
    }

    public Rectangle getBounds(){
        return PointsToPoly(NewPoints).getBounds();
    }
}

I'd like to know what's actually going wrong with this code, and if there's a better way around what I'm trying to achieve (rotating polygons). Here's where I render and rotate the polygons:

g2.setColor(Color.pink);
            for (PhysicsProp p : CurrentLevel.PhysicsObjects){
                g2.drawPolygon(p.PointsToPoly(p.NewPoints));
                p.rotateModel(0.001);
            }

Thanks for any help!

هل كانت مفيدة؟

المحلول

Try caching the centerpoint of the polygon, and always using that cached point as the point around which to rotate. Nothing guarantees that you'll calculate the same exact X/Y center point for any arbitrary polygon in any arbitrary rotation, so remove the risk (and the CPU cycles) and cache it once and just reuse from there.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top