如何使用 Three.js 检测 JavaScript 中两个对象之间的碰撞? [英] How to detect collision between two objects in JavaScript with Three.js?

查看:69
本文介绍了如何使用 Three.js 检测 JavaScript 中两个对象之间的碰撞?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里有很多关于碰撞检测的好东西,比如 Threex.colliders 或这里的代码片段,但实际上大多数东西都是旧的(一些函数如multiplyVector3被改变,其他的被删除.我有一个Object3D(字符模型)和一个世界(3D 模型:汽车、树木、建筑物等).我可以使用箭头键移动角色(在渲染循环中通过 translateX/Y 移动它.

There a lot of nice things for collision detection like threex.colliders or code snippets here on questions, but acutally the most stuff is old (some functions like multiplyVector3 are changed and other are removed. I have a Object3D (Character Model) and a World (3D Models: cars, trees, buildings etc.). I can move the Character with the arrow keys (moving it via translateX/Y in a render loop.

我想要的是角色模型和其他所有东西(除了地面和其他东西)之间的碰撞检测.所以我需要在 Object3D(字符)和 WorldObjects[](所有对象)之间进行碰撞检测.

What I want is a collision detection between the character model and everything else (except ground and some else). So I need a collision detection between Object3D (Character) and WorldObjects[] (all Objects).

那么,现在有几种方法可以获得想要的结果,哪一种是执行此操作的最佳(快速且可读)方式?现在的问题(也许)是否有效:当角色与其他任何东西发生碰撞时,我如何阻止他可以朝这个方向移动但他可以向左或向右后退?

So, now there are a few ways to get the wanted result maybe, which is the best (fast & readable) way to perform this? And now the problem (maybe) if it works: When the Character collides with anything else, how can I stop that he can move in this direction but he can go back, right or left?

推荐答案

您可以使用对象的边界框检测碰撞.边界框属于 THREE.Box3 类型,并且非常有用isIntersectionBoxcontainsBoxcontainsPoint 等方法,当您想要检测碰撞时,它们将满足您的所有需求.

You can detect collisions by using bounding boxes of objects. Bounding boxes are of type THREE.Box3 and have useful methods as isIntersectionBox, containsBox or containsPoint which will suit all your needs when you want to detect collisions.

使用它们就像这样简单:

Using them is as simple as this:

var firstObject = ...your first object...

var secondObject = ...your second object...

firstBB = new THREE.Box3().setFromObject(firstObject);

secondBB = new THREE.Box3().setFromObject(secondObject);

var collision = firstBB.isIntersectionBox(secondBB);

collision 如果盒子相互碰撞/碰撞,则为真.这让您对如何使用边界框有一个印象.

collision will be true if the boxes are colliding/hitting each-other. This gives you an impression on how you can use bounding boxes.

您还可以查看此示例.我认为这对你很有用.

You can also check this example out. I think it will be very useful for you.

您也许还应该查看 Physijs 库,它是一个 Three.js 的插件.

You should maybe also checkout the Physijs library which is a plugin to three.js.

有人有一个关于 Stackoverflow 的类似问题,您可能想要跟踪.

There is someone with a similar question on Stackoverflow that you might want to keep track of.

这篇关于如何使用 Three.js 检测 JavaScript 中两个对象之间的碰撞?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆