简体   繁体   中英

Rotate a point at a given angle

I wrote a code that should turn a point around another point counterclockwise. But it does not work correctly.

public boolean contains(double x, double y) {
    double ox = this.x.get() + (this.width.get()/2);
    double oy = this.y.get() + (this.height.get()/2);
    double theta = rotate.get() - (rotate.get() * 2);
    double px1 = Math.cos(theta) * (x-ox) - Math.sin(theta) * (y-oy) + ox;
    double py1 = Math.sin(theta) * (x-ox) + Math.cos(theta) * (y-oy) + oy;
    return shape.contains(px1, py1);
}

x, y - are the coordinates of the point to be rotated.

ox,oy - is the coordinates of the point around which you want to rotate.

rotate.get() - angle to rotate

Update: Changes in the code that solved the problem, who can come in handy:

    double px1 = Math.cos(Math.toRadians(theta)) * (x-ox) - Math.sin(Math.toRadians(theta)) * (y-oy) + ox;
    double py1 = Math.sin(Math.toRadians(theta)) * (x-ox) + Math.cos(Math.toRadians(theta)) * (y-oy) + oy;

Please check, if your rotate.get() will give you a degrees value (eg 45°) or a radians value (eg 0.5*pi). Math.sin() and Math.cos() will only accept radians.

To convert them you could use something like angle = Math.toRadians(45)

Although this is answered, another simple way to get this done is using the built-in method of Rotate class. This way you dont need to worry about the Math stuff ;)

Rotate r = new Rotate();
r.setPivotX(ox);
r.setPivotY(oy);
r.setAngle(angleInDegrees);
Point2D point = r.transform(new Point2D(x, y));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM