如何使对象在js中移动? [英] How to make object move in js?
问题描述
我正在尝试用 javascript 学习面向对象的编程,所以我尝试制作一个简单的游戏.我想做一个会动的角色.js里面有代码:
I'm trying to learn object oriented programming in javascript so I try to make a simple game. I would like to make a character that moves. There is the code in js:
function move(event)
{
var k=event.keyCode;
var chr = {
updown : function (){
var y=0;
if (k==38)
{--y;
}else if (k==40)
{++y;}
return y;
},
leftright : function (){
var x=0;
if (k==37)
{--x;
}else if (k==39)
{++x;}
return x;
}
};
chrId.style.top = (chr.updown())+"px";
chrId.style.left = (chr.leftright())+"px";
}
html:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="jumpOPP.css">
<script src="jumpOPP.js"></script>
</head>
<body onkeydown="move(event)">
<img id="chrId" src="TrackingDot.png" >
</body>
</html>
和 CSS:
#chrId {
position: relative;
top: 0px;
left: 0px;
}
当我按住上、下、左、右时,点只移动一个位置.如何让它一直移动 我拿着一些钥匙.我已经在没有 var char 的情况下移动了它.我使用函数 move(event) 然后是一个 switch,case 38, 37, 39 和 40 然后它改变 style.top 但我不能在一个对象中创建它.
When I press and hold up, down, left, right the dot moves only for a one place. How to make it moving whole time I' m holding some key. I have made it without var char to move. I used function move(event) and then a switch, cases 38, 37, 39 and 40 and then it change style.top but I can't make it in one object.
是否可以制作一个物体 chr = {objekt 运动、生命、力量...} 然后一个物体地面 = {一些停止 chr 的代码} 和其他相互作用的物体?有人可以为此推荐一个好的教程吗?:)谢谢
Is it possible to make a object chr = {objekt movement, life, power...} and then a object ground = {some code that stops the chr} and other interacting objects ? Can somebody recomend a good tutorial for that? :) Thank you
推荐答案
在这里工作 jsfiddle - http://jsfiddle.net/t5ya4j26/
Here working jsfiddle - http://jsfiddle.net/t5ya4j26/
您在始终等于 0 的范围内定义局部变量时出错.因此,要解决此问题,您必须获取元素的当前 left
和 top
,而不是定义 <代码>x = 0 和 y = 0
.
You error in define local variables in scopes that always will equal to 0. So for fix that, you must get current left
and top
of element, not define x = 0
and y = 0
.
function move(event) {
var k = event.keyCode,
chrId = document.getElementById('test'),
chr = {
updown: function () {
var y = parseInt(getComputedStyle(chrId).top);
if (k == 38) {
--y;
} else if (k == 40) {
++y;
}
return y;
},
leftright: function () {
var x = parseInt(getComputedStyle(chrId).left);
if (k == 37) {
--x;
} else if (k == 39) {
++x;
}
return x;
}
};
chrId.style.top = (chr.updown()) + "px";
chrId.style.left = (chr.leftright()) + "px";
}
document.addEventListener('keydown', move);
这篇关于如何使对象在js中移动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!