schteppe / cannon.js

A lightweight 3D physics engine written in JavaScript.
http://schteppe.github.com/cannon.js
MIT License
4.63k stars 700 forks source link

Hi, how to tell which Body collide with which? #470

Closed thusimon closed 2 years ago

thusimon commented 2 years ago

Hi, I am working on a FPS game, the arena is formed with a ground and four walls, they are all STATIC type. Players and their bullets are all DYNAMIC type, when I created all the bodies, I can set some custom data to the body, e.g: groundBody.name = 'ground' And when I get collide event by this

bulletBody.addEventListener('collide', (e: any) => {
  console.log(e);
})

How can I tell the bullet hit ground, walls or players? Thank you very much!

marcofugaro commented 2 years ago

You can access e.body to know the body it collided with.

https://github.com/pmndrs/cannon-es/blob/28248468d27496ff3b029aa141b0a930505f8ac3/examples/trigger.html#L49-L53

Tip, if you use cannon-es you can make use of the types as well, since you're using typescript.

thusimon commented 2 years ago

Thanks a lot Macro, that example fixed my issue. And it is good to know the cannon-es repo and all its examples.