gpt4 book ai didi

java - 游戏角色移动太快

转载 作者:行者123 更新时间:2023-11-30 11:26:52 25 4
gpt4 key购买 nike

我目前正在创建一个 Java 2D 游戏,我在其中接收来自用户的命令,将角色向上、向下、向左或向右移动一定距离。我目前正在使用 for 循环遍历用户输入并将字符串传递给 Player 类,该类将检查用户输入字符串是否与移动角色的方向之一匹配。当所有这些都被执行时,玩家似乎已经传送到终点位置。有没有办法让角色移动一定数量的像素,直到它到达目标位置,让玩家看起来好像自然地移动到该位置。

这是 movePlayer 函数,用于循环遍历 JTextFields,其中包含用户移动播放器的命令。来自每个文本字段的 strings 被传递到另一个函数:inputListener

public void movePlayer(){

for (int i = 0; i < userTextInput.size(); i++) {
inputListener(userTextInput.get(i).getText());
}
}

inputListener 检查用户输入的strings 是否匹配移动类型,并启动适当的方法来移动角色。

private void inputListener(String Input){

if(Input.equals("up")){
player.moveCharacterUp();

}else if(Input.equals("down")){
player.moveCharacterDown();

}else if(Input.equals("left")){
player.moveCharacterLeft();

}else if(Input.equals("right")){
player.moveCharacterRight();

}

}

这是根据 inputListener 运行的方法设置字符的 xy 位置的地方

public void moveCharacterUp(){
y -= moveSpeed;
}

public void moveCharacterDown(){
y += moveSpeed;
}

public void moveCharacterLeft(){
x -= moveSpeed;
}

public void moveCharacterRight(){
x += moveSpeed;
}

我正在使用的 Thread 的运行方法。

public void run(){

init();

long start;
long elapsed;
long wait;

while(running){

start = System.nanoTime();

update();
draw();
drawToScreen();

elapsed = System.nanoTime() - start;
wait = targetTime - elapsed / 1000000;

if(wait < 0) wait = 5;

try{
Thread.sleep(wait);

}catch(Exception e){
e.printStackTrace();
}

}
}

最佳答案

我过去这样做的方法是创建一个 targetXtargetY
然后我递增 xy 直到它们等于 targetXtargetY

int x = 0; //Character's x position
int y = 0; //Character's y position
int targetX = 0; //Character's target x position
int targetY = 0; //Character's target y position
int moveSpeed = 2; //the speed at which the character moves
int moveAmt = 20; //amount the character is set to move every time it is told to move

void setTarget(int targetX, int targetY) //sets targetX and targetY, doesn't need to be called at all
{
this.targetX = targetX;
this.targetY = targetY;
}

void moveCharacter(int x, int y) //moves the character, doesn't need to be called at all
{
this.x = x;
this.y = y;
}

void updatePosition() //initiates/continues movement, should be called every frame
{
if(Input.equals("up")) {
setTarget(targetX, targetY - moveAmt);

} else if(Input.equals("down")) {
setTarget(targetX, targetX + moveAmt);

} else if(Input.equals("left")) {
setTarget(targetX - moveAmt, targetX);

} else if(Input.equals("right")) {
setTarget(targetX + moveAmt, targetX);

}

if(y > targetY) {
player.moveCharacter(x, y - moveSpeed);

} else if(y < targetY) {
player.moveCharacter(x, y + moveSpeed);

} else if(x > targetX) {
player.moveCharacter(x - moveSpeed, y);

} else if(x < targetX) {
player.moveCharacter(x + moveSpeed, y);

}
}

关于java - 游戏角色移动太快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19595656/

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