jquery实现角色移动
时间: 2023-08-12 12:10:00 浏览: 40
要使用 jQuery 实现角色移动,你需要先确定角色移动的方式和场景。以下是一个简单的例子,实现在一个固定场景中的角色移动:
HTML:
```html
<div id="scene">
<div id="player"></div>
</div>
```
CSS:
```css
#scene {
width: 500px;
height: 300px;
border: 1px solid black;
position: relative;
}
#player {
width: 50px;
height: 50px;
background-color: red;
position: absolute;
left: 0;
top: 0;
}
```
JavaScript:
```javascript
$(document).ready(function() {
var player = $('#player');
var scene = $('#scene');
$(document).keydown(function(e) {
// 获取当前角色的位置
var pos = player.position();
switch(e.which) {
case 37: // 左
pos.left -= 10;
break;
case 38: // 上
pos.top -= 10;
break;
case 39: // 右
pos.left += 10;
break;
case 40: // 下
pos.top += 10;
break;
}
// 确保角色不会超出场景边界
if (pos.left < 0) pos.left = 0;
if (pos.top < 0) pos.top = 0;
if (pos.left + player.width() > scene.width()) pos.left = scene.width() - player.width();
if (pos.top + player.height() > scene.height()) pos.top = scene.height() - player.height();
// 移动角色
player.css(pos);
});
});
```
这个例子中,我们首先创建了一个固定场景(`#scene`)和一个角色(`#player`),并将角色的位置初始化为场景的左上角。然后,我们绑定了 `keydown` 事件,根据用户按下的方向键来移动角色。最后,我们检查了角色是否移出了场景边界,并更新了角色的位置。