Skip to content Skip to sidebar Skip to footer

How To Make This Object Move Faster

In my code I make an object (A man sprite) move 1 pixel every time an arrow key is pressed. When you hold down the arrow key, the man is very very slow. I tried increasing the amou

Solution 1:

try it, i just re-write the whole code for you. now i use an interval for each 100 milliseconds

var myElement = document.getElementById("character");

var move_left = false;
var move_up = false;
var move_right = false;
var move_down = false;

setInterval(function (){
	if (move_left) myElement.style.left = (getIntfromStyle(myElement.style.left) - 1) + 'px';
	if (move_up) myElement.style.top = (getIntfromStyle(myElement.style.top) - 1) + 'px';
	if (move_right) myElement.style.left = (getIntfromStyle(myElement.style.left) + 1) + 'px';
	if (move_down) myElement.style.top = (getIntfromStyle(myElement.style.top) + 1) + 'px';
}, 100);

// with this function, you dont need topStyle & left variables to store previous positions
// you can get current positioin easilysily
function getIntfromStyle(in_style) {
	return parseInt(in_style.replace('px', ''));
}

// i use keyboard to tell code when character should be moved and when must stop
document.onkeydown = function(e) {
    e = e || window.event;
    switch(e.which || e.keyCode) {
		case 37: // left
			move_left = true;
			break;
        case 38: // up
			move_up = true;
			break;
        case 39: // right
			move_right = true;
			break;
        case 40: // down
			move_down = true;
			break;
        default: return; // exit this handler for other keys
	}
	e.preventDefault(); // prevent the default action (scroll / move caret)
}

document.onkeyup = function(e) {
    e = e || window.event;
    switch(e.which || e.keyCode) {
		case 37: // left
			move_left = false;
			break;
        case 38: // up
			move_up = false;
			break;
        case 39: // right
			move_right = false;
			break;
        case 40: // down
			move_down = false;
			break;
	}
}
<div id="character"  style="background:red;width:20px;height:20px;position:fixed;display:block;left:0;top:0"></div>

Post a Comment for "How To Make This Object Move Faster"