简体   繁体   English

使用2D Canvas进行碰撞检测

[英]Collision Detection using 2D Canvas

I have some code that works pretty well, but could someone explain how this works to prevent collision in a video game? 我有一些运行良好的代码,但是有人可以解释一下如何防止视频游戏中的碰撞吗? What does this code actually mean? 此代码实际上是什么意思?

var checkCollision = function (bugs) {
   if(player.y + 131 >= bugs.y + 90
      && player.x + 25 <= bugs.x + 88
      && player.y + 73 <= bugs.y + 135
      && player.x + 76 >= bugs.x + 11) {
          console.log('YOU LOSE!');
      }
}

This is a common collision detection approach. 这是一种常见的碰撞检测方法。 Firstly each object, that being the player and the bug , have their position along with a width and height to them: 首先,每个对象,即playerbug ,都有其位置以及widthheight

在此处输入图片说明

Now if we look at one of the conditions of the form: player.x + A >= bugs.x + B we have a line: 现在,如果我们查看以下形式的条件之一: player.x + A >= bugs.x + B我们会有一行:

在此处输入图片说明

Place four lines together and you get a collision box: 将四行放在一起,您将获得一个碰撞盒:

Here is how collisions tend to look like: 这是碰撞趋向的样子:

if (player.x < bug.x + bug.width       // Player X is to the left of the bug's right
&& player.x + player.width > bug.x     // Player X is the to right of the bug's left
&& player.y < bug.y + bug.height       // Player Y is above the bottom of the bug
&& player.height + player.y > bug.y) { // Player Y is below the top of the bug
    // found a collision
}

This is an overlap between the player and the bug : 这是playerbug之间的重叠:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM