gpt4 book ai didi

Java - 向游戏添加控件的最佳方式

转载 作者:行者123 更新时间:2023-12-02 00:12:31 25 4
gpt4 key购买 nike

我正在用 Java 制作 2D 游戏,我使用 KeyListener 和一些 boolean 值来检测按键。但问题是,当我按住一个键时,玩家半秒不会移动,然后开始移动。有谁知道如何解决这个问题吗?

公共(public)无效keyPressed(...){玩家X+=3;}如有任何答案,我们将不胜感激。

最佳答案

有多种方法可以处理java中的游戏控件,但我更喜欢的方法是包含一个名为..让我们说“Key.class”的类

在 Key.class 中我们可以有:

public class Key{
// Creating the keys as simply variables
public static Key up = new Key();
public static Key down = new Key();
public static Key left = new Key();
public static Key special = new Key();

/* toggles the keys current state*/
public void toggle(){
isDown = !isDown;
}

public boolean isDown;
}

现在我们有了一个类,如果按下某些键,我们就可以访问该类,但首先我们需要确保按键 .isDown 函数能够正确切换。我们在实现 KeyListener 的类中执行此操作。

假设我们有“Controller.class”

package game;
// Importing the needed packages
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.HashMap;

public class Controller implements KeyListener{
//Assigning the variable keys to actual letters
public Controller(Main main){
bind(KeyEvent.VK_W, Key.up);
bind(KeyEvent.VK_A, Key.left);
bind(KeyEvent.VK_S, Key.down);
bind(KeyEvent.VK_D, Key.right);
bind(KeyEvent.VK_SPACE, Key.special);
mainClass = main;
}

@Override
public void keyPressed(KeyEvent e) {
other[e.getExtendedKeyCode()] = true;
keyBindings.get(e.getKeyCode()).isDown = true;
}

@Override
public void keyReleased(KeyEvent e) {
other[e.getExtendedKeyCode()] = false;
keyBindings.get(e.getKeyCode()).isDown = false;
}

public boolean isKeyBinded(int extendedKey){
return keyBindings.containsKey(extendedKey);
}

@Override
public void keyTyped(KeyEvent e) {
}


public void bind(Integer keyCode, Key key){
keyBindings.put(keyCode, key);
}

public void releaseAll(){
for(Key key : keyBindings.values()){
key.isDown = false;
}
}

public HashMap<Integer, Key> keyBindings = new HashMap<Integer, Key>();
public static boolean other[] = new boolean[256];

}

现在这个类将为我们处理所有的 keyBindings,并且假设您为 Canvas 添加 KeyListener 或您的游戏在其上运行的任何内容将起作用并相应地更改 Key.up/down/left/right/special。

现在最后一步是实现所有这些,以高效、轻松地移动我们的角色。

假设您在游戏中的实体有 update() 方法,该方法会运行每个刻度或类似的东西。我们现在可以简单地添加到其中

if(Key.up.isDown) y+=3;

或者在您的情况下,我们可以将其放入主类中,并以与游戏滴答循环中相同的方式执行操作。

if(Key.right.isDown) PlayerX += 3;

关于Java - 向游戏添加控件的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12448267/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com