沿着圆圈的Java画布旋转点

时间:2016-10-16 20:03:33

标签: java canvas rotation

我正在尝试使用Java制作一个小行星重拍,而我在按下按钮时使播放器(三角形)旋转时遇到问题。我已经查找了方法和数学,使三角形的点旋转,但我还没弄清楚如何使用公式。对你的帮助表示感谢。谢谢!

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;

import Main.GameObject;
import Main.ID;

public class Player extends GameObject {

    public float x1 = 16 + xPos;
    public float y1 = 0 + yPos;
    public float x2 = 0 + xPos;
    public float y2 = 48 + yPos;
    public float x3 = 32 + xPos;
    public float y3 = 48 + yPos;

    public float centerX = xPos + 16;
    public float centerY = yPos - 24;

    public Point2D.Float center = new Point2D.Float(xPos + 16, yPos - 24);

    public Point2D.Float p1 = new Point2D.Float(x1, y1);
    public Point2D.Float p2 = new Point2D.Float(x2, y2);
    public Point2D.Float p3 = new Point2D.Float(x3, y3);

    public Player(float startX, float startY, ID id) {
        super(startX, startY, id);
        this.xPos = startX;
        this.yPos = startY;
        this.id = id;

    }

    public void tick() {

    }

    public void render(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        g2.setColor(Color.WHITE);

        g2.draw(new Line2D.Float(p1, p2));
        g2.draw(new Line2D.Float(p2, p3));
        g2.draw(new Line2D.Float(p3, p1));
    }

    public Rectangle getBounds() {
        return null;
    }

    public void keyPressed(KeyEvent e) {
        int key = e.getKeyCode();

        if(key == KeyEvent.VK_RIGHT) {
            //Rotate triangle here
        }
    }
}

1 个答案:

答案 0 :(得分:0)

围绕原点(0,0)旋转单个点。

float rot = 2.0; // angle in radians
Point2D.Float p1 = new Point2D.Float(10.0,10.0);
Point2D.Float p1Rotated = new Point2D.Float(0,0);
float dx = Math.cos(rot);
float dy = Math.sin(rot);
p1Rotated.x = p1.x * dx + p1.y * -dy;
p1Rotated.y = p1.x * dy + p1.y * dx;

因此,对于一个中心位于0,0的三角形,请对每个点执行上述操作,然后通过将偏移量添加到每个点来定位三角形。

float rot = 2.0; // angle in radians
float x = 100.0; // space ship center at 100,100
float y = 100.0; 
Point2D.Float p1 = new Point2D.Float(10.0,10.0);
Point2D.Float p2 = new Point2D.Float(-10.0,10.0);
Point2D.Float p3 = new Point2D.Float(0.0,-10.0);
Point2D.Float p1R = new Point2D.Float(0,0);
Point2D.Float p2R = new Point2D.Float(0,0);
Point2D.Float p3R = new Point2D.Float(0,0);
float dx = Math.cos(rot);
float dy = Math.sin(rot);
p1R.x = p1.x * dx + p1.y * -dy + x;
p1R.y = p1.x * dy + p1.y *  dx + y;
p2R.x = p2.x * dx + p2.y * -dy + x;
p2R.y = p2.x * dy + p2.y *  dx + y;
p3R.x = p3.x * dx + p3.y * -dy + x;
p3R.y = p3.x * dy + p3.y *  dx + y;