我正在制作一个简单的游戏,其中有一个朝向鼠标的对象(一个带有矩形桶的正方形)。旋转部分工作得很好,但我希望对象在沿 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) {
}
}
非常感谢你的帮忙!!