如何在JS中创造一个角色

时间:2017-12-07 20:37:54

标签: javascript jquery character

我知道如何使用箭头键移动角色,但我如何发信号通知我想要角色的哪个图像

这是关于让它在箭头键上移动的代码,但是如何标记图像是角色呢?



///// store key codes and currently pressed ones
var keys = {};
    keys.LEFT = 37;
    keys.RIGHT = 39;

///// store reference to character's position and element
var character = {
  x: 100,
  y: 100,
  element: document.getElementById("character")
};

///// key detection (better to use addEventListener, but this will do)
document.body.onkeyup = 
document.body.onkeydown = function(e){
  var kc = e.keyCode || e.which;
  keys[kc] = e.type == 'keydown';
};

///// character movement update
var moveCharacter = function(dx, dy){
  character.x += dx||0;
  character.y += dy||0;
  character.element.style.left = character.x + 'px';
  character.element.style.top = character.y + 'px';
};

///// character control
var detectCharacterMovement = function(){
  if ( keys[keys.LEFT] ) {
    moveCharacter(-1);
  }
  if ( keys[keys.RIGHT] ) {
    moveCharacter(1);
  }
};

///// game loop
setInterval(function(){
  detectCharacterMovement();
}, 1000/24);




如果你能帮忙谢谢! (:我是Javascript的新手。

1 个答案:

答案 0 :(得分:0)

你可能想要这样的东西。在页面正文中添加角色的图像并为其指定id =" character" 。也可以像下面的代码段一样使用初始CSS



///// store key codes and currently pressed ones
var keys = {};
    keys.LEFT = 37;
    keys.RIGHT = 39;

///// store reference to character's position and element
var character = {
  x: 100,
  y: 10,
  element: document.getElementById("character")
};

///// key detection (better to use addEventListener, but this will do)
document.body.onkeyup = 
document.body.onkeydown = function(e){
   
  var kc = e.keyCode || e.which;
  keys[kc] = e.type == 'keydown';
};

///// character movement update
var moveCharacter = function(dx, dy){
  character.x += dx||0;
  character.y += dy||0;
  character.element.style.left = character.x + 'px';
  character.element.style.top = character.y + 'px';
};

///// character control
var detectCharacterMovement = function(){
  if ( keys[keys.LEFT] ) {
    moveCharacter(-1);
  }
  if ( keys[keys.RIGHT] ) {
    moveCharacter(1);
  }
};

///// game loop
setInterval(function(){
  detectCharacterMovement();
}, 1000/24);

#character{
  position:absolute;
  width: 50px;
  height: 50px;
  left: 100px;
  top: 10px;
}
.wrap{
  position:relative
}

<body>
<span>Click on Mario and use LEFT/RIGHT arrows to move it</span>
<div class="wrap">
<img src="https://rocketdock.com/images/screenshots/Mario-Icon.jpg" id="character"/>
</div>
</body>
&#13;
&#13;
&#13;