2D碰撞优化 四叉树碰撞检测算法

2023-10-07 00:20

本文主要是介绍2D碰撞优化 四叉树碰撞检测算法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

最近公司的小游戏项目贪吃蛇大作战出现了一些优化问题,当游戏玩到后期蛇会变得很长很长,食物也越来越多,游戏就会变得很卡,因为蛇的碰撞使用cocos creator中自带的Collider去检测食物和蛇身体,随着游戏的进行就造成了碰撞体越来越多,变得卡顿,查阅了一些资料,了解到了四叉树碰撞检测算法,所以我将游戏整体的检测进行了一下优化。

代码参考地址 https://github.com/timohausmann/quadtree-js

首先研究一下四叉树算法的原理

QuadTree四叉树顾名思义就是树状的数据结构,其每个节点有四个孩子节点,可将二维平面递归分割子区域。QuadTree常用于空间数据库索引,3D的椎体可见区域裁剪,甚至图片分析处理。QuadTree最常被游戏领域使用到的碰撞检测。采用QuadTree算法将大大减少需要测试碰撞的次数,从而提高游戏刷新性能。

1.就是把一块2d的区域,等分成四个象限

2.当更多的对象被添加到四叉树里时,它们最终会被分为四个子节点。将完全处于某一个象限的物体存储在该象限对应的子节点下,当然,也存在跨越多个象限的物体,我们将它们存在父节点中。如果某个象限内的物体的数量过多,它会同样会分裂成四个子象限,以此类推:

3.上图中右下角区域当蛇(白块表示)处于当前位置,会判断此区域内蛇的矩形所在象限的食物(绿块表示),提取出当前可计算的食物(绿块),进行计算,其他区域的食物(白框格子)不计算。这样就大大减少了计算量

代码如下:

class Quadtree {/** Quadtree Constructor* @param Object bounds            bounds of the node { x, y, width, height }* @param Integer max_objects      (optional) max objects a node can hold before splitting into 4 subnodes (default: 10)* @param Integer max_levels       (optional) total max levels inside root Quadtree (default: 4) * @param Integer level            (optional) deepth level, required for subnodes (default: 0)*/constructor (bounds, max_objects, max_levels, level) {this.max_objects    = max_objects || 10;this.max_levels     = max_levels || 4;this.level  = level || 0;this.bounds = bounds;this.objects    = [];this.nodes      = [];};/** Split the node into 4 subnodes*/split = function() {var nextLevel   = this.level + 1,subWidth    = this.bounds.width/2,subHeight   = this.bounds.height/2,x           = this.bounds.x,y           = this.bounds.y;        //top right nodethis.nodes[0] = new Quadtree({x       : x + subWidth, y       : y, width   : subWidth, height  : subHeight}, this.max_objects, this.max_levels, nextLevel);//top left nodethis.nodes[1] = new Quadtree({x       : x, y       : y, width   : subWidth, height  : subHeight}, this.max_objects, this.max_levels, nextLevel);//bottom left nodethis.nodes[2] = new Quadtree({x       : x, y       : y + subHeight, width   : subWidth, height  : subHeight}, this.max_objects, this.max_levels, nextLevel);//bottom right nodethis.nodes[3] = new Quadtree({x       : x + subWidth, y       : y + subHeight, width   : subWidth, height  : subHeight}, this.max_objects, this.max_levels, nextLevel);};/** Determine which node the object belongs to* @param Object pRect      bounds of the area to be checked, with x, y, width, height* @return Array            an array of indexes of the intersecting subnodes *                          (0-3 = top-right, top-left, bottom-left, bottom-right / ne, nw, sw, se)*/getIndex = function(pRect) {var indexes = [],verticalMidpoint    = this.bounds.x + (this.bounds.width/2),horizontalMidpoint  = this.bounds.y + (this.bounds.height/2);    var startIsNorth = pRect.y < horizontalMidpoint,startIsWest  = pRect.x < verticalMidpoint,endIsEast    = pRect.x + pRect.width > verticalMidpoint,endIsSouth   = pRect.y + pRect.height > horizontalMidpoint;    //top-right quadif(startIsNorth && endIsEast) {indexes.push(0);}//top-left quadif(startIsWest && startIsNorth) {indexes.push(1);}//bottom-left quadif(startIsWest && endIsSouth) {indexes.push(2);}//bottom-right quadif(endIsEast && endIsSouth) {indexes.push(3);}return indexes;};/** Insert the object into the node. If the node* exceeds the capacity, it will split and add all* objects to their corresponding subnodes.* @param Object pRect        bounds of the object to be added { x, y, width, height }*/insert = function(pRect) {var i = 0,indexes;//if we have subnodes, call insert on matching subnodesif(this.nodes.length) {indexes = this.getIndex(pRect);for(i=0; i<indexes.length; i++) {this.nodes[indexes[i]].insert(pRect);     }return;}//otherwise, store object herethis.objects.push(pRect);//max_objects reachedif(this.objects.length > this.max_objects && this.level < this.max_levels) {//split if we don't already have subnodesif(!this.nodes.length) {this.split();}//add all objects to their corresponding subnodefor(i=0; i<this.objects.length; i++) {indexes = this.getIndex(this.objects[i]);for(var k=0; k<indexes.length; k++) {this.nodes[indexes[k]].insert(this.objects[i]);}}//clean up this nodethis.objects = [];}};/** Return all objects that could collide with the given object* @param Object pRect        bounds of the object to be checked { x, y, width, height }* @Return Array            array with all detected objects*/retrieve = function(pRect) {var indexes = this.getIndex(pRect),returnObjects = this.objects;//if we have subnodes, retrieve their objectsif(this.nodes.length) {for(var i=0; i<indexes.length; i++) {returnObjects = returnObjects.concat(this.nodes[indexes[i]].retrieve(pRect));}}//remove duplicatesreturnObjects = returnObjects.filter(function(item, index) {return returnObjects.indexOf(item) >= index;});return returnObjects;};/** Clear the quadtree*/clear = function() {this.objects = [];for(var i=0; i < this.nodes.length; i++) {if(this.nodes.length) {this.nodes[i].clear();}}this.nodes = [];};    
}

使用方法:先创建一个 myFoodTree,再用 insert 方法将所有节点插入到myFoodTree中,通过 retrieve 方法传入蛇头自身的矩形信息,得到相对应的所有食物,在进行计算。

//创建一个quadtree 初始化蛇头的矩形信息
initQuadTree(){this.myFoodTree = new Quadtree({x: 0,y: 0,width: 1136,height: 640});this.snakeHeadRect = {x: 0,y: 0,width: 20,height: 20};this.foodList = [];for(let i = 0; i < 10; i++){this.foodList.push({x : this.random(-1136 / 2,1136 / 2),y : this.random(-1136 / 2,1136 / 2),width : this.random(4, 32),height : this.random(4, 32),})}
},//随机
random: function (min, max) {return Math.floor(Math.random() * (max - min + 1) + min)
},//将所有食物插入
insertFood(){for(let i = 0;i < this.foodList.length;i++){this.myFoodTree.insert({x: foodList[i].x,y: foodList[i].y,width: foodList[i].width,height: foodList[i].height,})}
},//将蛇头的矩形添加参数内 获取可以计算的食物
checkFoodCollision(){var candidates = this.myFoodTree.retrieve(this.snakeHeadRect);//TODO..
},

 

这篇关于2D碰撞优化 四叉树碰撞检测算法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/154865

相关文章

Deepseek使用指南与提问优化策略方式

《Deepseek使用指南与提问优化策略方式》本文介绍了DeepSeek语义搜索引擎的核心功能、集成方法及优化提问策略,通过自然语言处理和机器学习提供精准搜索结果,适用于智能客服、知识库检索等领域... 目录序言1. DeepSeek 概述2. DeepSeek 的集成与使用2.1 DeepSeek API

Tomcat高效部署与性能优化方式

《Tomcat高效部署与性能优化方式》本文介绍了如何高效部署Tomcat并进行性能优化,以确保Web应用的稳定运行和高效响应,高效部署包括环境准备、安装Tomcat、配置Tomcat、部署应用和启动T... 目录Tomcat高效部署与性能优化一、引言二、Tomcat高效部署三、Tomcat性能优化总结Tom

解读Redis秒杀优化方案(阻塞队列+基于Stream流的消息队列)

《解读Redis秒杀优化方案(阻塞队列+基于Stream流的消息队列)》该文章介绍了使用Redis的阻塞队列和Stream流的消息队列来优化秒杀系统的方案,通过将秒杀流程拆分为两条流水线,使用Redi... 目录Redis秒杀优化方案(阻塞队列+Stream流的消息队列)什么是消息队列?消费者组的工作方式每

Oracle查询优化之高效实现仅查询前10条记录的方法与实践

《Oracle查询优化之高效实现仅查询前10条记录的方法与实践》:本文主要介绍Oracle查询优化之高效实现仅查询前10条记录的相关资料,包括使用ROWNUM、ROW_NUMBER()函数、FET... 目录1. 使用 ROWNUM 查询2. 使用 ROW_NUMBER() 函数3. 使用 FETCH FI

C#使用HttpClient进行Post请求出现超时问题的解决及优化

《C#使用HttpClient进行Post请求出现超时问题的解决及优化》最近我的控制台程序发现有时候总是出现请求超时等问题,通常好几分钟最多只有3-4个请求,在使用apipost发现并发10个5分钟也... 目录优化结论单例HttpClient连接池耗尽和并发并发异步最终优化后优化结论我直接上优化结论吧,

Java内存泄漏问题的排查、优化与最佳实践

《Java内存泄漏问题的排查、优化与最佳实践》在Java开发中,内存泄漏是一个常见且令人头疼的问题,内存泄漏指的是程序在运行过程中,已经不再使用的对象没有被及时释放,从而导致内存占用不断增加,最终... 目录引言1. 什么是内存泄漏?常见的内存泄漏情况2. 如何排查 Java 中的内存泄漏?2.1 使用 J

Python中的随机森林算法与实战

《Python中的随机森林算法与实战》本文详细介绍了随机森林算法,包括其原理、实现步骤、分类和回归案例,并讨论了其优点和缺点,通过面向对象编程实现了一个简单的随机森林模型,并应用于鸢尾花分类和波士顿房... 目录1、随机森林算法概述2、随机森林的原理3、实现步骤4、分类案例:使用随机森林预测鸢尾花品种4.1

MySQL不使用子查询的原因及优化案例

《MySQL不使用子查询的原因及优化案例》对于mysql,不推荐使用子查询,效率太差,执行子查询时,MYSQL需要创建临时表,查询完毕后再删除这些临时表,所以,子查询的速度会受到一定的影响,本文给大家... 目录不推荐使用子查询和JOIN的原因解决方案优化案例案例1:查询所有有库存的商品信息案例2:使用EX

MySQL中my.ini文件的基础配置和优化配置方式

《MySQL中my.ini文件的基础配置和优化配置方式》文章讨论了数据库异步同步的优化思路,包括三个主要方面:幂等性、时序和延迟,作者还分享了MySQL配置文件的优化经验,并鼓励读者提供支持... 目录mysql my.ini文件的配置和优化配置优化思路MySQL配置文件优化总结MySQL my.ini文件

正则表达式高级应用与性能优化记录

《正则表达式高级应用与性能优化记录》本文介绍了正则表达式的高级应用和性能优化技巧,包括文本拆分、合并、XML/HTML解析、数据分析、以及性能优化方法,通过这些技巧,可以更高效地利用正则表达式进行复杂... 目录第6章:正则表达式的高级应用6.1 模式匹配与文本处理6.1.1 文本拆分6.1.2 文本合并6