- Home /
2D Object Collision - How To?
Hello everyone, I'll go straight to the point.
I've created 2 objects. ObjectA & ObjectB.
One is static(ObjectB) and one(ObjectA) has a script to go forward(towards ObjectB).
I want to add a Debug.Log when ObjectA collides(enters bounding box) of ObjectB.
How can I Implement this? I know I can do this w/RigidBody and wo/Physics.
Where my question is going is, my gameplay is a 2D Zeldaish Moving world.
What would be your best approach to do the Debug.Log. and How?
Thanks for your time and answers!
Answer by wibble82 · Mar 06, 2014 at 06:37 PM
The solution is triggers!
This is a key part of the docs to read: http://docs.unity3d.com/Documentation/ScriptReference/Collider.OnTriggerEnter.html
Add colliders to both objects, and a rigid body to Object A (at least 1 object involved has to have a rigid body for triggers to work).
If you don't want Object A to move under physics, set its rigid body to 'kinematic' - that means it exists in the physics world but you just move it via script rather than using proper physics.
Set Object B's collider to be a trigger (its in the properties). This will mean that when object A enters the collider it will call 'OnTriggerEnter' on any scripts on either object.
That should do it for the scenario you describe. It's a little different if you want objects to be bouncing around under physics instead (you use the OnCollisionEnter function instead) but the same principle applies.
@wibble82 Is there any difference if Im doing this on 2D? I tried adding box collider and then rigidBody2D but I had a warning "Can't add component 'Rigidbody2D' to Bullet because it conflicts with the existing 'BoxCollider' derived component!" also if its possible, how can I tell ObjectB that ObjectA collided with it?(as in if added another Object, how could I deter$$anonymous$$e which Object collided with B?)
Add Physics2D Box colliders. And for triggers there is a seperate set of functions for 2D
Answer by Max_power1965 · May 24, 2020 at 03:48 PM
I also had really a lot of problems when configuring the collision between game objects. After years I wrote every tips in this article https://gamedevelopertips.com/unity-collision-detection-2d/, I'm sure it'll be helpful if you want to set up properly you collider/triggers property.
Your answer
Follow this Question
Related Questions
Creating a teleportation gun 1 Answer
Horizontal gravity on One gameobject 2 Answers
Game objects sliding when frozen z-axis? 0 Answers
instantiate a gameobject or rigidbody? 1 Answer
How to determine the direction of an object to the player. 1 Answer