【发布时间】:2021-11-21 01:05:22
【问题描述】:
我正在尝试构建一个类似于 Jetpack Joyride 的游戏,在该游戏中,用户可以按住空格向上,放手向下。我有一个重力测试版本运行良好,但我仍在试图弄清楚如何测试以查看是否按住空格键。我的想法是,按住空格键的时候可以设置spaceHeld为true,不按下的时候设置为false。这是我的代码:
import java.awt.event.*;
import javax.swing.*;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Calendar;
public class Game {
JFrame frame;
JLabel player;
boolean grounded = false;
int velocity = 0;
int finalY = 0;
boolean spaceHeld = false;
Action spaceAction;
Game() {
frame = new JFrame("Nicholas Seow-Xi Crouse");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1920, 1080);
frame.setLayout(null);
player = new JLabel();
player.setBackground(Color.red);
player.setBounds(10, 1800, 50, 50);
player.setOpaque(true);
spaceAction = new SpaceAction();
player.getInputMap().put(KeyStroke.getKeyStroke("SPACE"), "spaceAction");
player.getActionMap().put("spaceAction", spaceAction);
frame.add(player);
frame.setVisible(true);
Timer flightTime = new Timer();
TimerTask flight = new TimerTask() {
public void run() {
if(velocity > -5) {
velocity -= 1;
}
else{
velocity = -5;
}
if (finalY < -61) {
finalY = finalY + velocity;
}
else{
finalY = -61;
}
player.setLocation(player.getX(), player.getY() + finalY);
if (player.getY() <= 0){
cancel();
velocity = 0;
finalY = 0;
player.setLocation(player.getX(), 0);
}
}
};
Timer gravityTime = new Timer();
TimerTask gravity = new TimerTask() {
//creates a timer run method that simulates the falling gravity when not grounded
public void run() {
if(velocity < 5){
velocity += 1;
}
else{
velocity = 5;
}
//creates the variable the tells where the player is located
if (finalY < 61) {
finalY = finalY + velocity;
}
else{
finalY = 61;
}
player.setLocation(player.getX(), player.getY() + finalY);
if (player.getY() >= 1000){
cancel();
velocity = 0;
finalY = 0;
player.setLocation(player.getX(), 990);
}
}
};
if (grounded == false && spaceHeld == false ) {
gravityTime.scheduleAtFixedRate(gravity, 0, 33);
}
if (grounded == false && spaceHeld == true ) {
flightTime.scheduleAtFixedRate(flight, 0 ,33);
}
}
//Creates the SpaceAction method that recieves input from the keyboard and moves the player downward
public class SpaceAction extends AbstractAction {
public void actionPerformed(ActionEvent e) {
spaceHeld = true;
//creates the grounded variable the tells the computer whether or not the player is on the ground
}
}
} ```
the spaceHeld boolean is used to see if space is held to change values, while the grounded boolean tells the program that the user is on the ground. Help is appreciated!
【问题讨论】:
-
您有问题吗?
-
您可以使用 key down 和 key up 事件来了解按钮何时被按下以及何时再次释放。
标签: java key-bindings