本篇文章给大家介绍一下使用 JavaScript 怎么利用键盘事件实现人物行走效果?(附代码). 有一定的参考价值, 有需要的朋友可以参考一下, 希望对大家有所帮助.
描述:
小时候喜欢玩的一个游戏, 魔塔, 实现了人物的行走, 以及跳跃, 当然是 2D 的效果.
使用的图:
效果图:
实例代码:
- <!DOCTYPE html>
- <HTML lang="en">
- <head>
- <meta charset="UTF-8">
- <title>
- Title
- </title>
- <style>
- HTML { background-color: deepskyblue; } div { width: 32px; height: 32px;
- background-image: url("img/Actor01-Braver03.png"); position: absolute;
- }
- </style>
- </head>
- <body>
- <div>
- </div>
- <script>
- var key = 0;
- var bool = false;
- var speed = 2; // 每次行走的距离
- var actor; // 人物 div
- const HEIGHT = 33; // 人物的高
- const WIDTH = 32; // 人物的宽
- var arr = [1, 3, 2, 0]; //4 排图像 代表 下 左 右 上
- var num = 0;
- var jumpBool = false;
- var actorSkinSpeed = 8;
- var jumpSpeed = -15;
- init();
- function init() {
- Windows.addEventListener("keydown", keyHandler);
- Windows.addEventListener("keyup", keyHandler);
- actor = document.querySelector("div");
- setInterval(animation, 16);
- // 按键驱动不能实现 实现的是通过按键触发相应动画 实现我们的人物的帧动画 跳转
- }
- function keyHandler(e) {
- bool = e.type === "keydown";
- key = e.keyCode;
- if (!bool) {
- num = 0;
- actor.style.backgroundPositionX = -num * WIDTH + "px";
- }
- if (key === 32 && !jumpBool) { // 跳跃 空格驱动
- jumpBool = true;
- }
- }
- function animation() {
- jump();
- if (!bool) return;
- walk(); // 单方向行走 实现
- changeDirection(); // 方向确定时 内部行走的实现
- }
- function jump() {
- if (!jumpBool) return;
- jumpSpeed += 1;
- if (jumpSpeed === 15) {
- jumpBool = false;
- jumpSpeed = -15;
- return;
- }
- actor.style.top = actor.offsetTop + jumpSpeed + "px";
- }
- function changeDirection() {
- actorSkinSpeed--;
- if (actorSkinSpeed > 0) return;
- actorSkinSpeed = 8;
- num++;
- if (num > 3) num = 0;
- actor.style.backgroundPositionX = -num * WIDTH + "px";
- }
- function walk() {
- switch (key) {
- case 37:
- // 左 *1 第二排
- actor.style.left = actor.offsetLeft - speed + "px";
- actor.style.backgroundPositionY = -arr[0] * HEIGHT + "px";
- break;
- case 38:
- // 上 *3 第四排
- actor.style.top = actor.offsetTop - speed + "px";
- actor.style.backgroundPositionY = -arr[1] * HEIGHT + "px";
- break;
- case 39:
- // 右 *2 第三排
- actor.style.left = actor.offsetLeft + speed + "px";
- actor.style.backgroundPositionY = -arr[2] * HEIGHT + "px";
- break;
- case 40:
- // 下 *0 第一排
- actor.style.top = actor.offsetTop + speed + "px";
- actor.style.backgroundPositionY = -arr[3] * HEIGHT + "px";
- break;
- }
- }
- </script>
- </body>
- </HTML>
更多 web 开发 https://www.html.cn/ 知识, 请查阅 HTML 中文网 !!
来源: http://www.css88.com/web/javascript/17517.html