- Home /
Collision With Character Controller
Hey, Im new to unity but find it very interesting ^^
Ive bin struggeling with a problem for several hours now, and I can cleary see that i need some help with it.
I have a turret firing balls into my world, and when the balls hit my character(First Person Character Controller) i want the game to stop (gameover)
But i dont know how to do this.
Can anyone link me a tutorial or a script that could do this, thank you very much in advance ;)
Answer by RoflJOE · Dec 05, 2010 at 10:54 PM
Okay this seems to work..
function OnCollisionEnter (other : Collision)
{
if (other.gameObject.name == "FirstPersonController") {
print("Game Over");
}
}
OnCollisionEnter doesn't work on Character controller and it only works on Rigidbody
OnCollisionEnter does work on character controller. Character Controller inherits from Collider, that has OnCollisionEnter
It may appear to work if your object happens to have a Rigidbody, but if all it has is a Character controller OnCollisionEnter will not fire.
Answer by Justin Warner · Dec 05, 2010 at 04:35 PM
Get the distance between the fire ball (Prefab?) and the player using Vector3.Distance(FIREBALL,PLAYER);
Then do an if statement to check if the fireball hit the player... If so, then start a new scene, where it shows they lost, or if you want to keep the background, tweak a pause game script... Search for one of those!
=)
Answer by RoflJOE · Dec 05, 2010 at 04:56 PM
I was thinking about: Can i somehow put a tag on the character controller and tell the ball script that when it collides with something that has that tag the game will pause or shift to another scene? ;) RoflJOE 58 secs ago
Answer by L5D7 · Mar 09, 2012 at 07:43 AM
I know this is old but I've had the same problem for a little while now and have come up with a very useful solution. I don't know how efficient it is, but it does work.
In the OnControllerColliderHit function you want to send a message to the object you've collided with that contains the name of the function you want to call and the ID of the object you hit, just to be safe.
/* In the script attached to the character */
function OnControllerColliderHit (hit : ControllerColliderHit) {
hit.gameObject.SendMessage("RecieveMessage", hit.gameObject.GetInstanceID());
}
/* In the script attached to the object */
function Recievemessage (id) {
if(id == gameObject.GetInstanceID()) {
print id;
}
}
So essentially the CharacterController hits the object then tells the object "hey, I hit you." Seems to work in my game. Hope this helps.
This is the right way to do it.
Object $$anonymous$$essages are the shit.
A good solution indeed, but not entirely correct. OnControllerColliderHit() is called only when the character is moving. If the character is standing still, and something hits him, OnControllerColliderHit() won't be called.