Saturday, June 1, 2024
 Popular · Latest · Hot · Upcoming
153
rated 0 times [  156] [ 3]  / answers: 1 / hits: 58180  / 10 Years ago, sun, august 17, 2014, 12:00:00

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


More From » 2d-games

 Answers
48

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

[#69750] Thursday, August 14, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ayleen

Total Points: 447
Total Questions: 88
Total Answers: 109

Location: Belize
Member since Mon, Jun 20, 2022
2 Years ago
;