我试图创建一个自上而下的太空船RPG,我似乎无法让它正确移动。它不会以正确的角度转动,例如,如果我有一个70度角,它将以45度角移动。有人可以帮忙吗?如果你想测试它看看我的意思,我可以用netbeans构建它。
package games;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.AffineTransform;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Rotation extends JPanel implements KeyListener{
private static double i = 0, inc = 0.1, iBase, speed = 0, maxTurnSpeed = 2;
private static int xPos = 100, yPos = 100, width = 100, height = 50;
static boolean pressedA = false, pressedD = false, slowdown = false;
public static void main(String[] args) throws InterruptedException {
System.out.println(i);
JFrame f = new JFrame();
Rotation r = new Rotation();
f.add(new Rotation());
f.setSize(600, 600);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.addKeyListener(r);
while(true){
move();
accelerate();
f.repaint();
Thread.sleep(10);
}
}
public static void move(){
xPos += speed * Math.cos(Math.toRadians(i));
yPos += speed * Math.sin(Math.toRadians(i));
System.out.println(i);
}
public static void accelerate(){
//=========Rotational speed acceleration========
if(i>= 360)
i=0;
if(i<= -360)
i=0;
if(pressedA)
i-=inc;
if(pressedD)
i+=inc;
if(inc<maxTurnSpeed && !slowdown && (pressedA || pressedD))
inc+= 0.01;
if(slowdown && inc>=0.02) {
inc-=0.2;
if(inc <= 0.02){
slowdown = false;
pressedA = false;
pressedD = false;
inc = 0;
}
if(pressedA)
i-=inc;
if(pressedD)
i+=inc;
}
//=========Frontal speed Acceleration=========
//i = Math.round10(i, -2);
//System.out.println(inc);
}
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setPaint(new Color(150, 150, 150));
g2d.fillRect(20, 20, 80, 50);
g2d.translate(180, -50);
g2d.rotate(Math.toRadians(i), xPos+width/2, yPos+height/2);
g2d.fillRect(xPos, yPos, width, height);
g2d.dispose();
//System.out.println("repainted");
}
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_W) {
System.out.println("W is pressed");
speed = 2;
slowdown = false;
maxTurnSpeed = 1;
}
if (keyCode == KeyEvent.VK_S) {
System.out.println("S is pressed");
speed = -1;
slowdown = false;
maxTurnSpeed = 1;
}
if (keyCode == KeyEvent.VK_A) {
System.out.println("A is pressed");
slowdown = false;
pressedA = true;
}
if (keyCode == KeyEvent.VK_D) {
System.out.println("D is pressed");
slowdown = false;
pressedD = true;
}
this.i=i;
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
speed = 0;
slowdown = true;
maxTurnSpeed = 2;
}
}