如何在CodeHS上的JS Graphics中做到平滑移动

问题描述 投票:0回答:1

如何在 CodeHS 上的 JS Graphics 中实现平滑移动。当我尝试用 Google 搜索时,我看到的所有内容都是针对您使用 HTML 执行 JS 的情况。

这是我当前的代码

let centerX = getWidth()/2;
let centerY = getHeight()/2;
let sqr;

function start(){
    createSquare();
    keyDownMethod(move);
}

function createSquare(){
    sqr = new Rectangle(50,50);
    sqr.setPosition(centerX-50/2,centerY-50/2)
    add(sqr);
}

function move(e){
    if(e.keyCode == Keyboard.letter('W') || e.keyCode == Keyboard.UP){
        sqr.move(0,-5);
    } else if(e.keyCode == Keyboard.letter('S') || e.keyCode == Keyboard.DOWN){
        sqr.move(0,5);
    } else if(e.keyCode == Keyboard.letter('A') || e.keyCode == Keyboard.LEFT){
        sqr.move(-5,0);
    } else if(e.keyCode == Keyboard.letter('D') || e.keyCode == Keyboard.RIGHT){
        sqr.move(5,0);
    }
}

起初我尝试将 move 1 放入 for 循环中,但它仍然基本上只是捕捉到一个位置。我也尝试这样做,但是使用 setTimeout 但不是等待每次循环时放置的毫秒数,它只是等待,然后循环执行设定的次数,即使设置的超时在循环内部。

javascript
1个回答
0
投票

您可以在

setTimer()
函数中添加
start()
调用,该函数调用可更改方块位置的函数。然后让您的键盘功能设置要添加到正方形当前 x 和 y 位置的值。

我还添加了按键向上功能,因此只有在按住按键时方块才会移动。

let centerX = getWidth()/2;
let centerY = getHeight()/2;
let sqr;
const moveIncrement = 2  // Larger number will move faster but jumpier
let xIncrement = 0
let yIncrement = 0

function start(){
    createSquare();
    keyDownMethod(keyDown);
    keyUpMethod(keyUp);
}

function createSquare(){
    sqr = new Rectangle(50,50);
    sqr.setPosition(centerX-50/2,centerY-50/2)
    add(sqr);
    
    setTimer(update, 16);
}

function keyDown(e){
    if(e.keyCode == Keyboard.letter('W') || e.keyCode == Keyboard.UP){
        yIncrement = -moveIncrement;
    } else if(e.keyCode == Keyboard.letter('S') || e.keyCode == Keyboard.DOWN){
        yIncrement = moveIncrement;
    } else if(e.keyCode == Keyboard.letter('A') || e.keyCode == Keyboard.LEFT){
        xIncrement = -moveIncrement;
    } else if(e.keyCode == Keyboard.letter('D') || e.keyCode == Keyboard.RIGHT){
        xIncrement = moveIncrement;
    }
}
function keyUp(e){
    if(e.keyCode == Keyboard.letter('W') || e.keyCode == Keyboard.UP){
        yIncrement = 0;
    } else if(e.keyCode == Keyboard.letter('S') || e.keyCode == Keyboard.DOWN){
        yIncrement = 0;
    } else if(e.keyCode == Keyboard.letter('A') || e.keyCode == Keyboard.LEFT){
        xIncrement = 0;
    } else if(e.keyCode == Keyboard.letter('D') || e.keyCode == Keyboard.RIGHT){
        xIncrement = 0;
    }
}
function update() {
    sqr.move(xIncrement, yIncrement);
}
© www.soinside.com 2019 - 2024. All rights reserved.