“播放器”是当我按下箭头键时向上,向下,向左和向右移动的对象。
当我按下并将左键或任何其他键按下时,“播放器”不会沿对角线方向移动。我正在使用Adobe Flash CS5和动作脚本3(As3),你能告诉我解决方案是什么吗?
stage.addEventListener(KeyboardEvent.KEY_DOWN, detectText);
function detectText(myevent:KeyboardEvent):void {
var up:Boolean = false;
var down:Boolean = false;
var left:Boolean = false;
var right:Boolean = false;
var speedOfplayer:Number = 5 ;
if (myevent.keyCode==39){
right = true ;
}
if (myevent.keyCode==37){
left = true ;
}
if (myevent.keyCode==38){
up = true ;
}
if (myevent.keyCode==40){
down = true ;
}
// if(right is true and left is not true)
if( right && !left ) {
player.x = player.x + speedOfplayer;
}
// if(up is true and down is not true)
if( up && !down ) {
player.y = player.y - speedOfplayer;
}
// if(down is true and up is not true)
if( down && !up ) {
player.y = player.y + speedOfplayer;
}
// if(down is true and up is not true)
if( left && !right ) {
player.x = player.x - speedOfplayer;
}
// Move diagonally
if( left && up && !right && !down ) {
player.y = player.y - speedOfplayer;
player.x = player.x - speedOfplayer;
}
if( right && up && !left && !down ) {
player.x = player.x + speedOfplayer;
player.y = player.y - speedOfplayer;
}
if( left && down && !right && !up ) {
player.x = player.x - speedOfplayer;
player.y = player.y - speedOfplayer;
}
if( right && down && !left && !up ) {
player.x = player.x + speedOfplayer;
player.y = player.y + speedOfplayer;
}
答案 0 :(得分:3)
你可能会过度复杂化。这可以通过以下方式完成。 KEY_DOWN侦听器发生的事情是它将报告按下的最后一个键。所以你需要一个ENTER_FRAME监听器来移动对象。并且因为ENTER_FRAME将继续调用所提供的功能,你需要捕获是否释放了一个键以将播放器的速度重置为0.
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
stage.addEventListener(Event.ENTER_FRAME, onTick);
var speedX:uint = 0;
var speedY:uint = 0;
function onKeyDown(event:KeyboardEvent):void {
var key:uint= event.keyCode;
if (key == Keyboard.UP) {
speedY = -5;
}
if (key == Keyboard.DOWN) {
speedY = 5;
}
if (key == Keyboard.LEFT) {
speedX = -5;
}
if (key == Keyboard.RIGHT) {
speedX = 5;
}
}
function onKeyUp(event:KeyboardEvent):void {
var key:uint= event.keyCode;
if (key == Keyboard.UP || key == Keyboard.DOWN) {
speedY = 0;
}
if (key == Keyboard.LEFT || key == Keyboard.RIGHT) {
speedX = 0;
}
}
function onTick(event:Event):void {
player.x += speedX;
player.y += speedY;
}