javascript - How to make object move in js? -


i'm trying learn object oriented programming in javascript try make simple game. make character moves. there 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 press , hold up, down, left, right dot moves 1 place. how make moving whole time i' m holding key. have made without var char move. used function move(event) , switch, cases 38, 37, 39 , 40 , change style.top can't make in 1 object.

is possible make object chr = {objekt movement, life, power...} , object ground = {some code stops chr} , other interacting objects ? can recomend tutorial that? :) thank you

here working jsfiddle - http://jsfiddle.net/t5ya4j26/

you error in define local variables in scopes equal 0. fix that, must current left , top of element, not define x = 0 , 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); 

Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -