gpt4 book ai didi

Java 游戏 - 按下按键

转载 作者:行者123 更新时间:2023-12-01 14:04:34 28 4
gpt4 key购买 nike

我正在做一个正交平铺 map Java 游戏,当我的船移动到 x 和 y 边界时,按方向键,它会停止移动(按预期),但如果我继续按该键,我的角色就​​会离开屏幕.

这是我正在使用的代码:

    @Override
public boolean keyDown(int keycode) {
ship = world.getShip();

switch(keycode){
case Keys.W:
if (ship.getPosition().y<28.5f){

ship.getVelocity().y = 1;}
else {
ship.getVelocity().y = 0;
}
break;
case Keys.S:
if (ship.getPosition().y1){
ship.getVelocity().y = -1;}
else {
ship.getVelocity().y = 0;
}
break;
case Keys.A:
if (ship.getPosition().x0)
ship.getVelocity().x = -1.5f;
else{
ship.getVelocity().x = 0;
}
break;
case Keys.D:
if (ship.getPosition().x<39){

ship.getVelocity().x = 1;
}
else{
ship.getVelocity().x = 0;
}
break;
default:
break;
}
return true;
}

@Override
public boolean keyUp(int keycode) {
ship = world.getShip();
switch(keycode){
case Keys.W:
if(ship.getVelocity().y == 1)
ship.getVelocity().y = 0;
break;
case Keys.S:
if(ship.getVelocity().y == -1)
ship.getVelocity().y = 0;
break;
case Keys.A:
if(ship.getVelocity().x == -1.5f)
ship.getVelocity().x = 0;
break;
case Keys.D:
if(ship.getVelocity().x == 1)
ship.getVelocity().x = 0;
break;

default:
break;
}
return true;
}

如果一直按下某个键,我该怎么做才能让我的飞船保持在屏幕上?

最佳答案

What should i do to keep my Ship on Screen if a key is keeping pushed?

首先使用当前的 API。 keyUp()keyDown() 自 JDK1.1 起已被弃用

首先阅读Motion Using the Keyboard有关如何处理此类问题的一些最新想法。代码示例执行基本的边界检查,以确保您无法将组件移出屏幕。

关于Java 游戏 - 按下按键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19019279/

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