How to detect collision of two objects in JavaScript using Three.js?

There are many nice things for detecting conflicts, such as trx.colliders or code snippets here, to questions, but, in fact, most things are deprecated (some functions, such as multiplyVector3, change and others are deleted. I have Object3D (Character Model) and the world (3D models: cars, trees, buildings, etc.). I can move the character using the arrow keys (moving it through translateX / Y to the rendering loop.

What I want is to detect a collision between the character model and everything else (except the earth and some others). Therefore, I need collision detection between Object3D (Character) and WorldObjects [] (all objects).

So, now there are several ways to get the desired result, which is the best (fast and readable) way to do it? And now the problem (maybe), if it works: When a character is faced with something else, how can I stop his movement in this direction, but can he go back or to the right?

+5
source share
1 answer

You can detect collisions using the bounding fields of objects. The bounding boxes are of type THREE.Box3 and have useful methods like isIntersectionBox , containsBox or containsPoint that will meet all your needs if you want to detect collisions.

Using them is just as easy:

 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 fields collide with each other. This gives you an idea of โ€‹โ€‹how to use bounding fields.

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

EDIT:

Perhaps you can also check out the Physijs library, which is a plugin for three .js.

There is someone with a similar question in Stackoverflow that you can track.

+8
source

Source: https://habr.com/ru/post/1213132/


All Articles