现在是添加玩家和 NPC 的时候了。 为此,您需要编写一个 Car 类。 它将有一个 Move() 方法,玩家可以使用该方法控制他的汽车。 NPC 的移动将通过 Update() 完成,它只是更改 Y 坐标。
class Car{ constructor(image, x, y) { this.x = x; this.y = y; this.image = new Image(); this.image.src = image; } Update() { this.y = speed; } Move(v, d) { if(v == “x”) //X-axis movement { this.x = d; //Offset // if(this.x this.image.width * scale > canvas.width) { this.x -= d; } if(this.x canvas.height) { this.y -= d; } if(this.y < 0) { this.y = 0; } } }}
让我们创建第一个要检查的对象。
var objects = [ new Car(“images/car.png”, 15, 10)]; //An array of game objectsvar player = 0; //the number of the object controlled by the player
现在您需要向 Draw() 函数添加一个用于绘制汽车的命令。
for(var i = 0; i < objects.length; i ){ ctx.drawImage ( objects[i].image, //Render image 0, //Initial X position in the image 0, //Initial Y-axis position in the image objects[i].image.width, //Image width objects[i].image.height, //Image height objects[i].x, //X-axis position on the canvas objects[i].y, //Y-axis position on the canvas objects[i].image.width * scale, //The width of the image on the canvas multiplied by the scale objects[i].image.height * scale //The height of the image on the canvas multiplied by the scale );}
在按下键盘时调用的 KeyDown() 函数中,您需要添加对 Move() 方法的调用。
function KeyDown(e){ switch(e.keyCode) { case 37: //Left objects[player].Move(“x”, -speed); break; case 39: //Right objects[player].Move(“x”, speed); break; case 38: //Up objects[player].Move(“y”, -speed); break; case 40: //Down objects[player].Move(“y”, speed); break; case 27: //Esc if(timer == null) { Start(); } else { Stop(); } break; }}
现在您可以检查渲染和控制。
碰撞时什么都没有发生,但这将在以后修复。 首先,您需要确保删除视图中丢失的对象。 这是为了避免堵塞 RAM。
在 Car 类中,我们添加值为 false 的字段 dead,然后在 Update() 方法中对其进行更改:
if(this.y > canvas.height 50){ this.dead = true;}
现在您需要更改游戏的更新功能,替换与对象关联的代码:
var hasDead = false; for(var i = 0; i < objects.length; i ){ if(i != player) { objects[i].Update(); if(objects[i].dead) { hasDead = true; } }} if(hasDead){ objects.shift();}
如果您不移除物体,当生成太多汽车时,游戏将开始降低计算机速度。
游戏物体碰撞
现在您可以开始实施碰撞。 为此,请为 Car 类编写一个方法 Collide(),它将检查汽车的坐标:
Collide(car){ var hit = false; if(this.y car.y) //If the objects are on the same line horizontally { if(this.x this.image.width * scale > car.x && this.x < car.x car.image.width * scale) //If the objects are on the same line vertically { hit = true; } } return hit;}
现在我们需要在 Update() 函数中添加碰撞检查:
var hit = false; for(var i = 0; i < objects.length; i ){ if(i != player) { hit = objects[player].Collide(objects[i]); if(hit) { alert(“You crashed!”); Stop(); break; } }}
这是游戏中的内容
碰撞时可以添加任何逻辑:
打开动画;
添加效果;;
删除对象;
健康状况的改变,等等。
所有这些都由开发人员自行决定。
结论
这是一个非常简单的游戏,但足以了解 JS 如何处理图形以及一般如何创建游戏。 您可以在 GitHub 存储库中找到图像和完整的游戏代码。
使用画布非常适合处理图形:它提供了很棒的功能并且不会过多地加载浏览器。 我们现在也有一个可用的 WebGL 库(示例和用法),它可以为您提供大量的性能和 3D 工作(canvas 无法做到这一点)。
理解 WebGL 可能很困难——也许相反,许多人对尝试 Unity 引擎更感兴趣,它知道如何编译项目以在浏览器中运行它们。
如发现本站有涉嫌抄袭侵权/违法违规等内容,请联系我们举报!一经查实,本站将立刻删除。