我正在用javascript编写游戏,我希望我的角色在块(等距png图像)下移动,而不是简单地滑过它们。有没有办法在他上下移动层时动态改变我的角色在 html 中的位置?
可以在这里看到游戏的当前进度,以显示我想要修复的内容:http: //dl.dropbox.com/u/18785762/Rust/index.html
角色创建和移动代码:
function mainchar(){
var mainchar = new Image();
mainchar.id = "mainChar";
mainchar.src = "Images/Char_01.png";
mainchar.style.top = "62px";
mainchar.style.left = "0px";
mainchar.style.position = "absolute";
window.addEventListener("keydown", movechar);
document.body.appendChild(mainchar);
}
function movechar(e){
var event = event || e;
var mainChar = document.getElementById("mainChar");
var top = Number(mainChar.style.top.replace("px",""));
var left = Number(mainChar.style.left.replace("px",""));
var stepSize = 32;
switch (event.keyCode){
case 37:
case 65: //left
left = left -27;
top = top -13;
break;
case 39:
case 68: // right
left = left + 27;
top = top +13;
break;
case 38:
case 87: // up
left = left +27;
top = top -13;
break;
case 40:
case 83: // down
left = left -27;
top = top +13;
break;
}
mainChar.style.top = top + "px";
mainChar.style.left = left + "px";
}