我正在做一个简单的游戏,其中有一个朝着鼠标的对象(一个带有矩形桶的正方形)。旋转部分效果很好,但是我希望对象在沿y轴按下按钮时移动,但直接向上移动,而不是相对于其旋转。现在,当按下按钮时,对象将朝其面对的方向向前移动。
无论对象处于哪个方向,如何将其直接沿y轴向上移动?
这是代码:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class RotationTestMain extends JFrame implements MouseMotionListener, KeyListener{
public static final long serialVersionUID = 666L;
public static final int SIZE = 50;
double xComponent;
double yComponent;
Image dbImage;
Graphics dbg;
int x;
int y;
int centerX;
int centerY;
JPanel area;
public RotationTestMain(){
area = new JPanel();
area.addMouseMotionListener(this);
addKeyListener(this);
x = 487;
y = 359;
centerX = x + SIZE/2;
centerY = y + SIZE/2;
add(area);
setSize(1024,768);
setLocationRelativeTo(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
@Override
public void paint(Graphics g){
dbImage = createImage(getWidth(), getHeight());
dbg = dbImage.getGraphics();
Graphics2D g2d = (Graphics2D) dbg;
draw(g2d);
g.drawImage(dbImage, 0, 0, this);
}
public void draw(Graphics2D g2d){
g2d.setColor(Color.BLACK);
g2d.rotate(calculateRotation(), centerX, centerY);
g2d.fillRect(x, y, SIZE, SIZE);
g2d.fillRect(centerX-5,y-20,10,25);
repaint();
}
public double calculateRotation(){
double rot;
if(yComponent >= 0){
rot = 3 * Math.PI - Math.atan(xComponent/yComponent);
}else {
rot = 2 * Math.PI - Math.atan(xComponent/yComponent);
}
return rot;
}
public static void main(String[] args) {
new RotationTestMain();
}
@Override
public void mouseDragged(MouseEvent m) {
centerX = x + SIZE/2;
centerY = y + SIZE/2;
xComponent = m.getX() - centerX;
yComponent = m.getY() - centerY;
}
@Override
public void mouseMoved(MouseEvent m) {
centerX = x + SIZE/2;
centerY = y + SIZE/2;
xComponent = m.getX() - centerX;
yComponent = m.getY() - centerY;
}
@Override
public void keyPressed(KeyEvent arg0) {
//TODO FIX THE MOVING PROBLEM
this.y -= 3;
}
@Override
public void keyReleased(KeyEvent arg0) {
}
@Override
public void keyTyped(KeyEvent arg0) {
}
}
非常感谢你的帮助!!
最佳答案
我认为问题出在这行g2d.rotate(calculateRotation(),centerX,centerY);
您不是旋转对象,而是整个g2d。因此,x,y轴也旋转,因为它们是g2d的一部分。
因此,当您执行此操作时。y-= 3;您确实沿y轴移动,但是y轴已旋转。
我建议找到一种旋转对象而不是整个g2d的方法。
关于java - Java 2D旋转和全局坐标?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15854450/