- Home /
What is the code for detecting a collision?
I have the problem that my character keeps clipping through walls. I've come up with the solution that, if I lower the speed of the character upon collision with the wall, it won't clip through.
I've looked through the Unity scripting reference, but I'm having a lot of trouble finding which code I'm supposed to use. What is the code for detecting a collision?
Answer by oliver-jones · May 25, 2012 at 05:31 PM
Is there a way for me to detect a collision on a specific collider?
Your link isn't correct, by the way, but I did do a google search for it, and I'm having trouble making sense of that. Could somebody please show me the individual parts of the collision codes in that page and what they mean/how they are used?
"Is there a way for me to detect a collision on a specific collider?"
void OnCollisionEnter(){ //no (parameters) //do stuff to whatever, without needing any info from the object hitting this object
//can I detect a specific collider here? No. Why? Cuz we didn't get any info from what hit us.
}
//------------------------------------------------------------
void OnCollisionEnter(Collision other){ //with (parameters)
//do stuff and get info if we want
// specific collider example :
if(other.collider.CompareTag("Player")){ //if the thing that hit us is tagged as Player, then...
//do stuff
}
//nothing else? ok, this thing only does stuff when "Player" hits us
}
(Collision yourVariableName) gets info from the colliding object.
From that you can access the other object as if this script were on it.
e.g. :
void OnCollisionEnter(Collision whatever){
if(whatever.collider.CompareTag("CubeZilla")){
//access a script on CubeZilla
SomeScriptOnCubeZilla otherScript = whatever.collider.GetComponent<SomeScriptOnCubeZilla>() ;
//change a variable value in that script from here
otherScript.somePublicBooleanVariable = false ;
//call a function on that script from here
otherScript.SomePublicFunction() ;
}
}
Contact Points ...
foreach(ContactPoint in yourVariableName.contacts){
Contact points are exactly what they're called. Points on the colliders at which contact between the two colliders was made upon collision.
Everything on those script reference pages in Blue Font is a link to more information. Click on them, and read everything you come across. Hope this helps people a bit (and hopefully the code chunks format correctly so I don't have to edit this post..)
If you want to check if a specific object/collider has hit, you can do:
function OnCollisionEnter(hit : Collision){
if(hit.collider.gameObject.tag == "YourTag"){
} }
Your answer
Follow this Question
Related Questions
Camera Colliding with Terrain 1 Answer
Gameover On Collision 1 Answer
How to let the player collide with animated objects? 0 Answers
How do i understand which gameObject is player touching ? 1 Answer
Mesh Collider doesn't work without reset 2 Answers