【问题标题】:How to make this object move faster如何让这个物体移动得更快
【发布时间】:2016-11-21 22:39:25
【问题描述】:

在我的代码中,每次按下箭头键时,我都会让一个对象(一个男人精灵)移动 1 个像素。当你按住方向键的时候,这个人非常非常慢。我尝试在每次按下键时增加量,但这不够平滑。有人能告诉我如何让他每次移动一个像素但每 100 毫秒移动一个像素吗?谢谢,感谢您的帮助。

    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';
}

【问题讨论】:

  • 请编辑您的问题并使用集成的 sn-p 或 jsfiddle.net 添加功能案例(我们没有您的 html 库)

标签: javascript html keypress


【解决方案1】:

试试看,我只是为你重新编写了整个代码。现在我每 100 毫秒使用一个间隔

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>

【讨论】:

  • 所以变量是var speed = const speed = 5;
  • @T.Bragg var speed = const speed = 5; 是什么意思我用 const 代替 var 因为 speed 值不能改变并且只定义一次,但你可以简单地改变 @ 987654325@转var
  • 我知道,我以为我错了,我试过了,但没用
  • 现在所做的只是将对象增加 5
  • 我如何让它顺利移动
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-02-23
  • 2014-12-30
  • 1970-01-01
  • 1970-01-01
  • 2016-03-24
  • 2017-08-04
  • 1970-01-01
相关资源
最近更新 更多