html5游戏对象移动不工作

html5游戏对象移动不工作,html,Html,我正在努力改进我正在创建的html5游戏,我正在尝试将玩家对象的移动放到游戏中,如下所示: var canvas = document.getElementById('myCanvas'); var context = canvas.getContext('2d'); theplayer = function(width, height, color, x, y) { this.width = width;

我正在努力改进我正在创建的html5游戏,我正在尝试将玩家对象的移动放到游戏中,如下所示:

var canvas = document.getElementById('myCanvas');
            var context = canvas.getContext('2d');

        theplayer = function(width, height, color, x, y)
        {
            this.width = width;
            this.height = height;
            this.color = color;
            this.speedx = 0;
            this.speedy = 0;
            this.x = x;
            this.y = y;    

            this.update=function()
            {
                context.fillStyle = color;
                context.fillRect(this.x,this.y,this.width,this.height);
            }

            this.newpos=function()
            {
                this.x += this.speedx;
                this.y += this.speedy;
            }

        }

        var theplayer = new theplayer(30, 30, "red", 10, 120);

        function clearboard()
        {
            context.clearRect(0,0,canvas.width,canvas.height);
        }

        function movement()
        {
            document.addEventListener("keydown",keyPressed, false);
            document.addEventListener("keyup",keyLifted, false);
        }

        function keyPressed(event)
        {
            var keyPressed = String.fromCharCode(event.keyCode);

            if (keyPressed == "W")
            {       
                theplayer.speedx += 1;
            }
            else if (keyPressed == "D")
            {   
               theplayer.speedy += 1;
            }
            else if (keyPressed == "S")
            {   
               theplayer.speedx -= 1;   
            }
            else if (keyPressed == "A")
            {   
                theplayer.speedy -= 1;
            }
        }

        var rungame = setInterval(function()
        {
           clearboard();
           theplayer.newpos();
           theplayer.update();
        }, 20);

该程序应使播放器使用WASD键控制播放器对象,但我无法将X和Y坐标的更改应用到“theplayer”对象的“newpos”功能中。我该如何解决这个问题?是否存在对WASD键进行多次按键操作的问题?

是否有错误?目前发生了什么?在plunker或其他类似服务上发布您的代码可能有助于我们确定问题。@Mathieu de Lorimier您的
移动
函数似乎从未被调用,因此从未添加键盘事件侦听器?它是在其他地方调用的吗?@Mathieu de Lorimier我可以知道如何让“theplayer.newpos”函数调用移动函数吗?应该在文档就绪或类似的情况下调用特定的函数(以便事件侦听器只添加一次)。这是相当基本的东西。我建议您看一本关于如何设置事件侦听器的JS教程。