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

て烟熏妆下的殇ゞ 提交于 2019-12-19 02:40:30

问题


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.

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?


回答1:


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 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.

EDIT:

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

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



来源:https://stackoverflow.com/questions/28453895/how-to-detect-collision-between-two-objects-in-javascript-with-three-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!