简体   繁体   English

如何使用Three.js检测JavaScript中两个对象之间的冲突?

[英]How to detect collision between two objects in JavaScript with Three.js?

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. 碰撞检测有很多很好的东西,例如问题上的trix.colliders或代码片段,但实际上大多数东西都是旧的(一些函数如multiplyVector3被更改而其他函数被删除。我有一个Object3D(角色模型)和一个世界(3D模型:汽车,树木,建筑物等)。我可以使用箭头键移动角色(在渲染循环中通过translateX / Y移动它)。

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). 所以我需要在Object3D(Character)和WorldObjects [](所有对象)之间进行碰撞检测。

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? 现在问题(可能)如果它起作用:当角色与其他任何东西发生碰撞时,我怎么能阻止他可以向这个方向移动但是他可以向后,向右或向左移动?

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. 包围盒类型的THREE.Box3和具有有用的方法为isIntersectionBoxcontainsBoxcontainsPoint当你想检测碰撞,这将满足您的所有需求。

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 will be true if the boxes are colliding/hitting each-other. 如果盒子相互碰撞/撞击,则collision将成立。 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. 我认为这对你非常有用。

EDIT: 编辑:

You should maybe also checkout the Physijs library which is a plugin to three.js. 你也许应该检查Physijs库,这是一个three.js的插件。

There is someone with a similar question on Stackoverflow that you might want to keep track of. 您可能希望跟踪Stackoverflow上有类似问题的人。

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

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