所以我试图在java中构建一个自上而下的太空射击游戏。
我是一个新手,但我已经很好地掌握了它,完美地制作pong。我的主要问题是,我似乎不能降低旋转。
我希望能够在方向键上按向右或向左键,并有一个基本的矩形,在用户输入的方向上围绕其中心旋转。
设置好后,我希望能够按箭头键前进或后退,使其朝着当前所面向的方向移动。
到目前为止,我所尝试的一切都影响了框架中的所有内容,而不仅仅是单个对象。从as2开始,旋转和对象在java中是非常不同的。
谁能帮我解释一下我该怎么做?
package spaceroyalgame;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.geom.AffineTransform;
public class SpaceRoyalGame extends JPanel implements KeyListener {
static double shipRotation=0, shipRotationSpeed=0, shipSpeed=0, TOPSPEED= 20;
static int shipy=50, shipx=50, shipWidth = 10, shipHeight = 20;
static int WorldWidth = 700, WorldHeight = 700;
static boolean slowdown = true;
public static void main(String[] args) throws InterruptedException {
SpaceRoyalGame game = new SpaceRoyalGame();
JFrame frame = new JFrame();
frame.add(game);
frame.setSize(WorldWidth,WorldHeight);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.addKeyListener(game);
while(true){
game.moveShip();
game.repaint();
Thread.sleep(10);
}
}
public void moveShip(){
if (shipSpeed != 0) {
shipx += shipSpeed;
}
if (shipRotationSpeed != 0) {
shipRotation += shipRotationSpeed;
}
}
public void paint (Graphics g){
super.paint(g);
setBackground(Color.black);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(Color.white);
Rectangle ship = new Rectangle(shipx,shipy,100,50);
g2d.rotate(Math.toRadians(shipRotation));
g2d.draw(ship);
g2d.fill(ship);
}
@Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
slowdown = false;
if (keyCode == KeyEvent.VK_W) {
//System.out.println("W is pressed");
shipSpeed = -2;
}
if (keyCode == KeyEvent.VK_S) {
//System.out.println("S is pressed");
shipSpeed = 2;
}
if (keyCode == KeyEvent.VK_A) {
System.out.println("A is pressed");
shipRotationSpeed = 1;
shipRotation += shipRotationSpeed * (shipSpeed/TOPSPEED);
}
if (keyCode == KeyEvent.VK_D) {
System.out.println("D is pressed");
shipRotationSpeed = -1;
shipRotation += shipRotationSpeed * (shipSpeed/TOPSPEED);
}
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
shipRotationSpeed = 0;
shipSpeed = 0;
}
}
尝试使用矢量。因为"A"one_answers"D"键会修改你当前的角度,所以你应该保留一个变量来跟踪角度。
从:x += speed * cos(θ)
y += speed * sin(θ)
如果你想加速/减速:
Δx = speed * cos(θ) * Δt + 1/2 * acceleration * Δt^2
Δy = speed * * sin(θ) * Δt + 1/2 * acceleration * Δt^2
Δt是最后一帧之间的时间。
这可能值得看看物理/运动学