How to make this object move faster

泪湿孤枕 提交于 2019-12-25 08:15:17

问题


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 amount each time the key is pressed but that is not smooth enough. Can somebody tell me how I can make him move one pixel each time but move one pixel every 100 milliseconds? Thanks I appreciate the help.

    function moveLeft() {
    var newLeft = left - 1;
    left = newLeft;
    myElement.style.left = newLeft + 'px';

}
function moveUp() {
    var newTop = topStyle - 1;
    topStyle = newTop;
    myElement.style.top = newTop + 'px';

}
function moveRight() {
    var newLeft2 = left + 1;
    left = newLeft2;
    myElement.style.left = newLeft2 + 'px';

}
function moveDown() {
    var newTop2 = topStyle + 1;
    topStyle = newTop2
    myElement.style.top = newTop2 + 'px';
}

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


来源:https://stackoverflow.com/questions/40730702/how-to-make-this-object-move-faster

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!