所以我试图为一个自上而下的射击游戏的小型测试游戏制作基础引擎。我大部分时间都处于向下旋转状态,但我不能让它在朝向它的方向上正确移动。 包游戏;
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;
private static int xPos = 0, yPos = 0, 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(-1*Math.PI*i/180);
yPos -= speed * Math.sin(-1*Math.PI*i/180);
System.out.println(i);
}
public static void accelerate(){
if(i>= 360)
i=0;
if(pressedA)
i-=inc;
if(pressedD)
i+=inc;
if(inc<2 && !slowdown && (pressedA || pressedD))
inc+= 0.01;
if(slowdown && inc>=0.02) {
inc-=0.2;
if(inc <= 0.02){
slowdown = false;
pressedA = false;
pressedD = false;
}
if(pressedA)
i-=inc;
if(pressedD)
i+=inc;
}
//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;
}
if (keyCode == KeyEvent.VK_S) {
System.out.println("S is pressed");
speed = -2;
//slowdown = false;
}
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;
}
-edit - 所以我认为这可能与轮换发生的地方有关。
答案 0 :(得分:0)
sin和cos函数的角度值必须以弧度为单位。 做这样的事情:
xPos += speed * Math.cos(-1*Math.PI*i/180);
这可能会解决您的问题