我是一名 html5 程序员爱好者,经验不多,目前正在开发一款需要移动玩家/图像的游戏。下面代码的问题是,每当我右键单击播放器时,播放器只会第一次移动,然后再也不会移动。我注意到间隔也不起作用,它只调用一次函数。此外,xNum 和 yNum 变量始终保持为 0(请注意,每次调用该函数时,我的控制台都会记录它们)。我不知道我是否解释了我希望代码做得足够好,如果我没有解释,我很抱歉。继续问你可能有的任何问题。感谢您的宝贵时间!
<html oncontextmenu="return false">
<head>
<title>test</title>
<style>
#cursor{
user-select: none;<!--disable highlighting of cursor-->
}
</style>
</head>
<body>
<img src="images/test1.png" id = "player" style = "margin-left: 300px;margin-top: 100px;position: absolute;">
<img src="" id = "cursor" style = "visibility: hidden;">
<script>
document.getElementById('cursor').ondragstart = function () { return false; };//disable dragging of cursor
window.onmousedown = function userClicked(event) {
if(event.button == 2){
var x = event.clientX;
var y = event.clientY;
var cursor = document.getElementById("cursor");
cursor.src = "images/testCursorWalk.gif";
cursor.style.visibility = "visible";
cursor.style.position = 'absolute';
cursor.style.left = x + 'px';
cursor.style.top = y + 'px';
setTimeout(function(){cursor.style.visibility = "hidden";cursor.src = "";},200)
//after cursor is shown call player walk
setInt(x,y);
}
}
function setInt(x,y){
var xNum = 0;
var yNum = 0;
var walk = setInterval(walkPlayer(x,y,xNum,yNum),100);
}
function walkPlayer(x,y,xN,yN){
var p = document.getElementById("player");
var style = p.currentStyle || window.getComputedStyle(p);
var ix = parseInt(style.marginLeft.substring(0,1));//get x
var iy = parseInt(style.marginTop.substring(0,1));//get y
var plx = document.getElementById("player").style.left;//method doesnt work
var ply = document.getElementById("player").style.top;//method doesnt work
var xNum = xN;
var yNum = yN;
//x-axis
if(ix > x){
xNum += 100;
document.getElementById("player").style.left = xNum+'px';
}
else if(ix < x){
xNum -= 100;
document.getElementById("player").style.left = xNum+'px';
}
//y-axis
if(iy > y){
ply += 1000 +'px';//doesnt work with variables like ply
} //...
else if(iy < y){ //...
ply -= 1000 +'px';//have to instead use the whole document.getElement...
}
if(iy == y && ix == x){
alert("destination reached!")
clearInterval(walk);//this wouldnt work as 'var walk' is private right?
}
}
</script>
</body>
</html>
最佳答案
setTimeout 和 mousedown 事件只触发一次。您可以使用 setInterval 来连续更新 Angular 色。然后在按下或释放鼠标时更改速度。
let position = 0
let speed = 0
let cursor = document.getElementById("cursor")
function updatePosition(){
position += speed
cursor.style.left = position + 'px'
}
function startWalking(){
cursor.src = "images/testCursorWalk.gif"
this.speed = 5
}
function stopWalking(){
cursor.src = "images/stop.gif"
this.speed = 0
}
window.addEventListener("mousedown", ()=> startWalking())
window.addEventListener("mouseup", ()=> stopWalking())
setInterval(()=>updatePosition(), 100)
关于Javascript - 在游戏中更改图像位置不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49950875/