我目前正在创建一个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();
}
}
这是根据x
y
和inputListener
位置的位置
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();
}
}
}
答案 0 :(得分:1)
我过去这样做的方法是创建targetX
和targetY
然后我增加x
和y
,直到它们等于targetX
和targetY
。
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);
}
}
答案 1 :(得分:0)
速度由变量moveSpeed设定。这可能设置为比您想要的更高的值,因此请尝试更改它。
答案 2 :(得分:0)
你的程序需要计算时间。该时间值将用于缩放moveSpeed。按下键并获取当前时间。当您要应用moveSpeed时,您必须再次获取时间并计算与之前时间的差异。这种差异将是您的比例因子。像这样:
private void inputListener(String Input){
lastTime = getTime();
}
public void moveCharacterUp(){
currTime = getTime();
y -= moveSpeed * (currTime - lastTime)
lastTime = currTime;
}