Javascript 平台游戏-运动

Javascript Platformer- Movement

我目前正在尝试我的第一个游戏项目并遇到了 运行 问题。我不确定为什么,但按下某个键时我的角色不会移动。我回顾了我正在使用的教程代码,我的代码是教程的逐字记录。

这可能是一个简单的修复,但我是网络开发新手,所以我真的很难调试。

我的代码:

<!DOCTYPE html>
<html>
<body onkeydown="keyDown(event)" onkeyup="keyUp(event)">
<canvas id="graphics" width=600 height=400 
        style="position:absolute;top:0;left:0;background-image:url('images/sky.png');">
</canvas>

<script>
    //VARIABLES
    var gameCanvas = document.getElementById("graphics");
    var grafx   = gameCanvas.getContext('2d');
    var player  = new Object("images/lookright.png",100,100);
    var isLeft  = false;
    var isRight = false;

    //EVENTS
    function keyDOWN(e) {
        if (String.fromCharCode(e.keyCode) == "97") isLeft = true;
        if (String.fromCharCode(e.keyCode) == "100") isRight = true;
    }

    function keyUp(e) {
        if (String.fromCharCode(e.keyCode) == "97") isLeft = false;
        if (String.fromCharCode(e.keyCode) == "100") isRight = false;
    }

    //MAINLOOP
    MainLoop();

    function MainLoop() {
        //PRE VARIABLE ADJUSTMENTS
        player.X += player.Velocity_X;
        player.Y += player.Velocity_Y;

        //LOGIC
        if (isLeft)  player.Velocity_X = -3;
        if (isRight) player.Velocity_X = 3;
        if (!isLeft && !isRight) player.Velocity_X = 0;

        //POST VARIABLE ADJUSTMENTS

        //RENDERING
        grafx.clearRect(0,0,gameCanvas.width,gameCanvas.height);
        grafx.drawImage(player.Sprite,player.X,player.Y);

        setTimeout(MainLoop, 1000/60);
    }

    function Object(img, x, y) {
        this.Sprite = new Image();
        this.Sprite.src = img;
        this.X = x;
        this.Y = y;
        this.Previous_X;
        this.Previous_Y;
        this.Velocity_X = 0;
        this.Velocity_Y = 0;
    }
</script>
</body>
</html>

JavaScript 区分大小写。 keyDOWNkeyDown 不一样。

如果出现问题,请使用开发人员工具(Chrome 中的 Ctrl+Shift+I 和 IE 中的 FF、F12)并检查“控制台”选项卡中的错误消息。在这种情况下,我很确定 JS 抱怨该函数不存在。

另外:String.fromCharCode(e.keyCode) == "97" 没有意义。 e.keyCode 是代表按下的键的数字,例如97 "a"。 String.fromCharCode() 需要一个数字和 returns 字符 table 中与该数字对应的字符,因此如果您调用 String.fromCharCode(97),您会返回 "a"。所以你基本上是在混合两种有效的方法来创建第三种不起作用的方法。它应该是以下之一:

if (e.keyCode == 97) isLeft = true;

if (String.fromCharCode(e.keyCode) == 'a') isLeft = true;

但是,你应该注意到 keyCode 属性 已被弃用,建议使用更友好的 key 属性,其中包含按下的键的 "name":

if (e.key == 'a') isLeft = true;