- Home /
other : question is too broad / unspecific
How do I check if an object is touching another object?
How do I check if the player is touching any object?
What I am trying to do is make it so I can jump if I am touching anything.
Start in the Unity Learn section : http://unity3d.com/learn/tutorials/modules
Answer by JackMini36 · Dec 20, 2014 at 02:12 AM
Use a collider on both objects. Also tag the objects, for example one could be "floor" and the other "player". Then use the OnCollisionEnter function to act accordingly if certain objects collide.
http://docs.unity3d.com/ScriptReference/Collider.OnCollisionEnter.html
for example if you want to be able to jump if your players touch on anything:
void OnCollisionEnter (Collider other)
{
canJump = true;
}
void OnCollisionExit (Collider other)
{
canJump = false;
}
then in your player script, enable the player to jump only if canJump is true.
I just get an error saying This message parameter has to be of type: collision.
i am modifing above answer a little bit. void OnCollisionEnter (Collision other) { canJump = true; }
void OnCollisionExit (Collision other) { canJump = false; }
To clarify this for future viewers: The script above mixes syntax from two different functions. One for Collision and one for colliders. Use either void OnTriggerEnter(Collider other) or void OnCollisionEnter(Collision collision). Either one could be used in this scenario and work just fine.
On Trigger happens when two colliders make contact or "collide", one has a rigidbody and is set as a trigger. Its easy enough to use for telling when two objects are touching one another and then making an event accessible only if they are touching as seen above.
On collision happens when two objects have a "collision" and at least one has a non-kinematic rigidbody making it good to use if you need physics to know the contact point or to only register the collision if a velocity threshold has been met for changing the result such as how loud a sound is based on the velocity of the impact.
Either will work but for a simple jump detection OnTriggerEnter may require an extra trigger collider if you also need a physics collider but still uses a fraction less resources when calculating the results as it is not reading a collision object. The difference is near meaningless at a small scale but may add up on a larger project. So generally speaking, you can use a trigger when you have an object which doesn't interact "physically" and a collision when they do.
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
how to morph character on collision enter with gameobject 1 Answer
Slicing Objects 1 Answer
End game then an Object is close to another object? 0 Answers
Basic Collision, Object + First Person 2 Answers