请问我这段代码哪里有问题啊,我这个按下一个键就一直动了,放开了也在动。我想做到的是按下一个键就朝一个方向一直动,放开了就不动
public class Player
{
int player_x = 0;
int player_y = 0;
int player_w = 16; //每格人物图象的宽
int player_h = 32; //每格人物图象的高
int player_dir = 4; //0为下,1为左,2为右,3为上,4为不动
int playerFrameIndex;//当前的贞
int player_speed = 2;
int old_dir;
boolean isUp = false;
boolean isDown = false;
boolean isLift = false;
boolean isRight = false;
public Player(int x,int y,int dir)
{
player_x = x;
player_y = y;
player_dir = dir;
}
public void draw(Graphics g,Image player,Image player4)
{
g.setClip(player_x, player_y, player_w, player_h);
g.drawImage(player, player_x - playerFrameIndex * player_w, player_y - player_dir * player_h, 20);
move();
}
void move()
{
switch(player_dir)
{
case 0:
player_y += player_speed;
break;
case 1:
player_x -= player_speed;
break;
case 2:
player_x += player_speed;
break;
case 3:
player_y -= player_speed;
break;
}
updata();
}
public void keyPressed(int keyCode)
{
switch(keyCode)
{
case KeyMap.KEY_2:
isUp = true;
break;
case KeyMap.KEY_UP:
isUp = true;
break;
case KeyMap.KEY_4:
isLift = true;
break;
case KeyMap.KEY_LEFT:
isLift = true;
break;
case KeyMap.KEY_6:
isRight = true;
break;
case KeyMap.KEY_RIGHT:
isRight = true;
break;
case KeyMap.KEY_8:
isDown= true;
break;
case KeyMap.KEY_DOWN:
isDown = true;
break;
}
setDirection();
}
public void keyReleased(int keyCode)
{
switch(keyCode)
{
case KeyMap.KEY_2:
isUp = false;
break;
case KeyMap.KEY_UP:
isUp = false;
break;
case KeyMap.KEY_4:
isLift = false;
break;
case KeyMap.KEY_LEFT:
isLift = false;
break;
case KeyMap.KEY_6:
isRight = false;
break;
case KeyMap.KEY_RIGHT:
isRight = false;
break;
case KeyMap.KEY_8:
isDown= false;
break;
case KeyMap.KEY_DOWN:
isDown = false;
break;
}
setDirection();
}
void setDirection()
{
if(!isLift && !isUp && !isRight && isDown) //如果只有isDown被激活,即isDown值为true
{
player_dir = 0; //则把人物的方向设置为0,0代表下
}
else if(isLift && !isUp && !isRight && !isDown) //如果只有isLift被激活,即isLift值为true
{
player_dir = 1; //则把人物的方向设置为1,1代表左
}
else if(!isLift && !isUp && isRight && !isDown) //如果只有isRight被激活,即isRight值为true
{
player_dir = 2; //则把人物的方向设置为2,2代表右
}
else if(!isLift && isUp && !isRight && !isDown) //如果只有isUp被激活,即isUp值为true
{
player_dir = 3; //则把人物的方向设置为3,3代表上
}
}
void updata()
{
playerFrameIndex++;
playerFrameIndex %= 3;
}
}
------解决方案--------------------------------------------------------
你写一个按键检测方法,把它放到run()里面,在这个方法外用boolean的变量is_key_down判断按键状态。keyPressed()里面写is_key_down=true;表示按键按下;在keyReleased()里写is_key_down=false;表示按键抬起。
代码:
- Java code
private int key1;//按键键值private boolean is_key_down;//按键状态/** *系统方法,按下按键 * */public void keyPressed(int key){ is_key_down=true; key1=key;//传参}/** *系统方法,抬起按键 * */public void keyReleased(int key){ is_key_down=false;}/** *你的代码中写在keyPressed里的switch语句 * */private void keySet(int key){ switch(key){ }}public void run(){ if(is_key_down) keySet(key1);//自定义方法}