Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize collision Detection by html5

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "html5 how to achieve collision detection", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "html5 how to achieve collision detection" bar!

For collision detection in Canvas, people often directly use the built-in collision detection functions of game engines (Cocos2d-JS, Egret) or physics engines (Box2D). Have you ever thought about their internal operating mechanism? The following will explain the basic collision detection techniques:

1. Collision detection based on rectangle

The so-called collision detection is to judge whether there is overlap between objects. Here we assume that the collision bodies discussed are all rectangular objects. In the following example, we will create two rect objects An and B (hereinafter referred to as AMagi B), where An is fixed, B moves with the mouse, and the console will prompt intercectals when Ameme B overlaps!

1. Create a Rect object

Here we create a new Rect.js, create a Rect object, and add a prototype method draw to it, which is drawn into the incoming canvas object (context) based on the properties (position, size) of the current object.

The code is as follows:

Function Rect {this.x = x; this.y = y; this.width = width; this.height = height;} Rect.prototype.draw = function (context) {context.save (); context.translate (this.x,this.y); context.fillRect

2. Get the mouse position

Because B needs to follow the mouse, we need to detect the current position of the mouse on the canvas. Create a Capturemouse function to detect mouse movement over the incoming document node (element) and return a mouse object (which contains the mouse's x _ line y coordinates).

The code is as follows:

Function Capturemouse (element) {var mouse= {element.addEventListener (event) {var x, y; if (event.pageX | | event.pageY) {x = event.pageX; y = event.pageY;} else {x = event.clientX+document.body.scrollLeft+ document.documentElement.scrollLeft Y = event.clientY+document.body.scrollTop+ document.documentElement.scrollTop;} x-= element.offsetLeft; y-= element.offsetTop; mouse.x = x; mouse.y = y;}, false); return mouse;}

3. Collision detection

To detect whether there is overlap in APerry B, we can first look at four cases where there is no overlap when discussing whether there is overlap, as shown below:

The following is the judgment of these four states:

1 、 rectB.y+rectB.height

< rectA.y 2、rectB.y >

RectA.x + rectA.width

3. RectB.y > rectA.y + rectA.height

4 、 rectB.x+rectB.width

< rectA.x 知道如何判断没有重叠的状态,那发生重叠的状态该如何判断呢?没错"取反"!,我们创建函数Interaect并添加到Init.js中,该函数传入两个Rect对象参数,当两Rect对象发生重叠将返回true。 代码如下: function Intersect(rectA,rectB) { return !(rectB.y+rectB.height < rectA.y || rectB.y >

RectA.x + rectA.width | | rectB.y > rectA.y + rectA.height | | rectB.x+rectB.width

< rectA.x)} 4、动画循环 新建animationjs,设置requestAnimationFrame()动画函数。 在循环体中将做以下两件事: "清空"当前canvas中内容,为绘制下一帧做准备。 检测A,B是否发生重叠,若重叠则在控制台输出interact!!! 检测当前鼠标在canvas上的移动并将鼠标位置更新到B的位置属性中。 根据新的位置属性重新绘制A,B(当然,A的位置不会更新但因为每次循环将清空canvas所以需要重新绘制) 代码如下: function drawAnimation() { window.requestAnimationFrame(drawAnimation); context.clearRect(0, 0, canvas.width, canvas.height); if(Intersect(rectA,rectB)){ console.log('interact!!!!'); } if(mouse.x){ rectB.x = mouse.x; rectB.y = mouse.y; } rectA.draw(context); rectB.draw(context);} 3、初始化 新建Init.js ,获取canvas元素并绑定鼠标移动检测,初始化Rect对象A和B,最后开启动画循环。 代码如下: _window.onload = function () { canvas = document.getElementById('collCanvas'); context = canvas.getContext('2d'); Capturemouse(canvas); rectA = new Rect(canvas.width/2,canvas.height/2,100,100); rectB = new Rect(100,100,100,100); drawAnimation();} 2、基于圆形的碰撞检测 说完矩形碰撞,我们再来聊聊圆形碰撞,同样我们将创建两个Circle对象A和B(以下简称A,B),其中A位置固定,B跟随鼠标移动,当A,B重叠时控制台将提示intercect!! 1、创建circle对象 function Circle(x,y,radius) { this.x = x; this.y = y; this.radius = radius;}Circle.prototype.draw = function(context){ context.save(); context.translate(this.x,this.y); context.beginPath(); context.arc(0,0,this.radius,0,Math.PI*2,false); context.fill(); context.restore();} 2、检测圆形碰撞 圆形间碰撞检测可以简单地通过两圆心间距离与两圆半径之和的比较做判断,当两圆心距离小于两圆半径之和时则发生碰撞。 所以我们首先需要做的是计算出两圆心间的距离,这里我们将用到两点间的距离公式 当取得两圆心间的距离之后将与两圆半径之和比较,如果距离小于半径之和则返回true。 现在我们更新Interaect函数。 代码如下: function Intersect(circleA,circleB) { var dx = circleA.x-circleB.x; var dy = circleA.y-circleB.y; var distance = Math.sqrt(dx*dx+dy*dy); return distance < (circleA.radius + circleB.radius);} 3、动画循环 更新animation.js,这里我们替换Rect对象为Circle对象。 代码如下: function drawAnimation() { window.requestAnimationFrame(drawAnimation); context.clearRect(0, 0, canvas.width, canvas.height); if(Intersect(circleA,circleB)){ console.log('interact!!!!'); } if(mouse.x){ circleB.x = mouse.x; circleB.y = mouse.y; } circleA.draw(context); circleB.draw(context);} 4、初始化 更新Init.js ,初始化Circle对象A和B,最后开启动画循环。 代码如下: _window.onload = function () { canvas = document.getElementById('collCanvas'); context = canvas.getContext('2d'); Capturemouse(canvas); circleA = new Circle(canvas.width/2,canvas.height/2,100); circleB = new Circle(100,100,100); drawAnimation();} 3、基于矩形与圆形间的碰撞检测 前面讲解都是单一形状间的碰撞检测,下面我们将检测矩形和圆形间的碰撞。 1、检测碰撞 和矩形检测一样,我们先看看没有发生碰撞的四种情况。 这四种状态的判断: Circle.y + Circle.radius < Rect.y Circle.x - Circle.radius >

Rect.x + Rect.width

Circle.y-Circle.radius > Rect.y + Rect.height

Circle.x + Circle.radius

< Rect.x 更新Interaect函数,将没有重叠的状态"取反",向该函数传入Rect对象和Circle对象,当Rect对象与Circle对象发生重叠将返回true。 代码如下: function Intersect(Rect,Circle) { return !(Circle.y + Circle.radius < Rect.y || Circle.x - Circle.radius >

Rect.x + Rect.width | | Circle.y-Circle.radius > Rect.y + Rect.height | | Circle.x + Circle.radius < Rect.x)}

2. Animation cycle

Update animation.js, where we follow the mouse movement of the circle object and detect collisions with the rect object in a fixed position.

The code is as follows:

Function drawAnimation () {window.requestAnimationFrame (drawAnimation); context.clearRect (0,0, canvas.width, canvas.height); if (Intersect (rect,circle)) {console.log ('interactful interaction among others');} if (mouse.x) {circle.x = mouse.x; circle.y = mouse.y;} circle.draw (context); rect.draw (context);}

3. Initialize

Update Init.js, initialize the Circle object and the Rect object, and finally start the animation loop.

The code is as follows:

_ window.onload = function () {canvas = document.getElementById ('collCanvas'); context = canvas.getContext (' 2d'); Capturemouse (canvas); circle = new Circle (100100100); rect = new Rect (canvas.width/2,canvas.height/2100100); drawAnimation () Thank you for your reading, the above is the content of "how to achieve collision detection in html5". After the study of this article, I believe you have a deeper understanding of how to achieve collision detection in html5, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report