Search code examples
javascript2d-games

How to make object move in js?


I'm trying to learn object oriented programming in javascript so I try to make a simple game. I would like to make a character that moves. There is the code in js:

  function move(event)
    {
var k=event.keyCode; 

var chr = {

    updown : function (){
            var y=0;
            if (k==38) 
                {--y;
            }else if (k==40)
                 {++y;}
            return y; 
        },

    leftright : function (){
        var x=0;
        if (k==37) 
            {--x;
        }else if (k==39) 
            {++x;}
        return x; 
            }


    };

    chrId.style.top = (chr.updown())+"px";
    chrId.style.left = (chr.leftright())+"px";

}

html:

    <!DOCTYPE html>
<html>
<head>

<link rel="stylesheet" type="text/css" href="jumpOPP.css">
<script src="jumpOPP.js"></script>
</head>

<body  onkeydown="move(event)">
<img id="chrId" src="TrackingDot.png" >


</body>
</html>

and CSS:

#chrId {
    position: relative;
    top: 0px;
    left: 0px;
}

When I press and hold up, down, left, right the dot moves only for a one place. How to make it moving whole time I' m holding some key. I have made it without var char to move. I used function move(event) and then a switch, cases 38, 37, 39 and 40 and then it change style.top but I can't make it in one object.

Is it possible to make a object chr = {objekt movement, life, power...} and then a object ground = {some code that stops the chr} and other interacting objects ? Can somebody recomend a good tutorial for that? :) Thank you


Solution

  • Here working jsfiddle - http://jsfiddle.net/t5ya4j26/

    You error in define local variables in scopes that always will equal to 0. So for fix that, you must get current left and top of element, not define x = 0 and y = 0.

    function move(event) {
    var k = event.keyCode,
        chrId = document.getElementById('test'),
        chr = {
            updown: function () {
                var y = parseInt(getComputedStyle(chrId).top);
                if (k == 38) {
                    --y;
                } else if (k == 40) {
                    ++y;
                }
    
                return y;
            },
    
            leftright: function () {
                var x = parseInt(getComputedStyle(chrId).left);
                if (k == 37) {
                    --x;
                } else if (k == 39) {
                    ++x;
                }
    
                return x;
            }
        };
    
    chrId.style.top = (chr.updown()) + "px";
    chrId.style.left = (chr.leftright()) + "px";
    }
    
    document.addEventListener('keydown', move);