user2980958 user2980958 - 11 months ago 65
Javascript Question

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)
}else if (k==40)
return y;

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

}; = (chr.updown())+"px"; = (chr.leftright())+"px";



<!DOCTYPE html>

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

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


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 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

Answer Source

Here working jsfiddle -

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) {
            } else if (k == 40) {

            return y;

        leftright: function () {
            var x = parseInt(getComputedStyle(chrId).left);
            if (k == 37) {
            } else if (k == 39) {

            return x;
    }; = (chr.updown()) + "px"; = (chr.leftright()) + "px";

document.addEventListener('keydown', move);