如何使对象在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)函数,然后使用了一个开关,分别是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 = {物体运动,寿命,功率...},然后使一个物体接地= {一些使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屋!