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 reend a good tutorial for that? :) Thank you
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 reend a good tutorial for that? :) Thank you
Share Improve this question edited Aug 17, 2014 at 19:20 PeeHaa 72.8k60 gold badges194 silver badges264 bronze badges asked Aug 17, 2014 at 19:15 Mislavoo7Mislavoo7 6971 gold badge7 silver badges16 bronze badges 1-
1
function
move()
must call itself again and again with a setTimeout, so it will be targeted to 60fps, and on keyUp, you must kill this repetition ofmove()
either via a flag variable or some other way (clearTimeout) – vsync Commented Aug 17, 2014 at 19:19
4 Answers
Reset to default 0Here working jsfiddle - http://jsfiddle/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);
I would remend that you use the <canvas>
element for stuff like this. But use window.setInterval(function, milliseconds)
to have it repeatedly run your 'move' function and then when a key is released, window.onkeyup
clear that interval.
clearInterval(intervalName);
This requires you to make a new event listener. Instead of having your event listener in body, use:
window.onkeydown = function(event) {
var k = event.which || event.keyCode; // This adds patibilty across all browsers
// Code to be run
}
I know that you are looking for the function in an object, but moving an element is really quick and easy with this, I just made this today for my beginners game:
var change = (parseInt(chrId.style.left.replace('%',''),10) + 3).toString() + "%"
chrId.style.left = change
The % signs can be replaced with 'px' if you are using pixel values to move, and the ' + 3 ' is how many pixels or percentage points you want your element to move per execution.
The same can be done for up by changing the 'left' to 'top'.
My code might not be to your liking, but I'm just trying to demonstrate how I work around this problem, I am positively sure that there are hundreds of better ways, but this one seems to save me a lot of trouble for a lot of other stuff.
Hope I was able understand the question and help though, sorry if I couldn't :)
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title> MOVEMENT </title>
</head>
<body>
<script type = "text/javascript">
//------------------------------------------------------------------------------
// VARIABLES are set here so they're GLOBAL (everything may access them)
//------------------------------------------------------------------------------
let lock_left = true
let lock_top = true
let lock_right = true
let lock_bottom = true
//------------------------------------------------------------------------------
let html; let htmls
let body; let bodys
let avatar; let avatars
//------------------------------------------------------------------------------
let avatar_x = 0
let avatar_y = 0
//------------------------------------------------------------------------------
// EVERY map will be an object, and every object needs a CREATE function that
// will happen only ONCE and an UPDATE function that will repeat itself
//------------------------------------------------------------------------------
const map_main =
{
create: function()
{
html = document.querySelector( "html" ); htmls = html.style
body = document.querySelector( "body" ); bodys = body.style
},
//--------------------------------------------------------------------------
update: function()
{
htmls.width = "100%"
htmls.height = "100%"
htmls.margin = "0"
bodys.width = "100%"
bodys.height = "100%"
bodys.margin = "0"
bodys.backgroundColor = "rgb( 120, 200, 80 )"
},
}
//------------------------------------------------------------------------------
const map_avatar =
{
create: function()
{
avatar = document.createElement( "div" ); avatars = avatar.style
body.appendChild( avatar )
},
//--------------------------------------------------------------------------
update: function()
{
avatars.width = "64px"
avatars.height = "64px"
avatars.backgroundColor = "rgb( 200, 80, 120 )"
avatars.position = "absolute"
avatars.top = avatar_y + "px"
avatars.left = avatar_x + "px"
},
}
//------------------------------------------------------------------------------
// BELOW are the 2 main gears of the engine
//------------------------------------------------------------------------------
// EVERY code that only needs to happen once is called here
const master_create = function()
{
map_main.create()
map_avatar.create()
}
//------------------------------------------------------------------------------
// EVERYTHING that needs constant updates is called here
const master_update = function()
{
map_main.update()
map_avatar.update()
movement()
window.requestAnimationFrame( master_update )
}
//------------------------------------------------------------------------------
// BELOW is showing how the keyboard affects the locks
//------------------------------------------------------------------------------
const press = function( pressed )
{
if( pressed.keyCode === 37 || pressed.keyCode === 69 ) lock_left = false
if( pressed.keyCode === 38 || pressed.keyCode === 82 ) lock_top = false
if( pressed.keyCode === 39 || pressed.keyCode === 70 ) lock_right = false
if( pressed.keyCode === 40 || pressed.keyCode === 68 ) lock_bottom = false
}
//------------------------------------------------------------------------------
const release = function( released )
{
if( released.keyCode === 37 || released.keyCode === 69 ) lock_left = true
if( released.keyCode === 38 || released.keyCode === 82 ) lock_top = true
if( released.keyCode === 39 || released.keyCode === 70 ) lock_right = true
if( released.keyCode === 40 || released.keyCode === 68 ) lock_bottom = true
}
//------------------------------------------------------------------------------
// BELOW will check the LOCKS and use them to change AVATAR_X and AVATAR_Y
//------------------------------------------------------------------------------
const movement = function()
{
if( lock_left === false ) avatar_x -= 10
if( lock_top === false ) avatar_y -= 10
if( lock_right === false ) avatar_x += 10
if( lock_bottom === false ) avatar_y += 10
}
//------------------------------------------------------------------------------
// BELOW we call the 2 gears and everything will work
//------------------------------------------------------------------------------
master_create() // will be called only ONCE
master_update() // will repeat forever due to "window.requestAnimationFrame()"
//------------------------------------------------------------------------------
// LISTENERS should go after the engine starts rolling
//------------------------------------------------------------------------------
body.addEventListener( "keydown", press, false )
body.addEventListener( "keyup", release, false )
//------------------------------------------------------------------------------
</script>
</body>
</html>