OnCollisionEnter() not detecting collisions

Hi,

I have a small sphere that follows the player’s cursor everywhere it goes, and I want an event to be called when that sphere hits an object in the world.

So far I have this code:

var cam : Camera;

function Update() {
var mousePos = Input.mousePosition;
mousePos.z = 175;
transform.position = cam.ScreenToWorldPoint(mousePos);
}

function OnCollisionEnter() {
Debug.Log("BAAA!");
}

This works fine for controlling the sphere’s position, but for some reason the collisions are just not detected! I’ve tried adding a rigidbody as well, but still nothing happens! :frowning:

Please help!

Are any of your objects set to “Is Trigger”?
If so they will not collide with your object.

Secondly, unless the sphere is a vital part of your graphics for the game, you should be using Raycasting to detect whether or not the cursor is hitting an object.
There are plenty of tutorials on how to do that out there.

do you need to set the “Tag” for the objects and redo script to look for objects with the tag? im not sure, but its an option?

OnCollisonEnter/OnTriggerEnter only work for the collider attached to the object the script is attached to.

If your script is attached to your camera, it will only register collisions on the camera’s collider.

Place your OnCollisionEnter code in a separate script and attach that script to the sphere, and voila.

Did you ever consider attaching a character controller to your sphere? If you move the character controller instead (the character controller will move your object), it should collide with objects that have a collision box or a rigid body

this script worked fine for my start Unity - Scripting API: CharacterController.Move

Hi! I think it was you, I helped on the Unity Forums a few days ago, with the sphere following mouse problem.

You’re using cam.ScreenToWorldPoint. This means your script is using a camera component. This means your script is attached to the camera, that you’re using to detect the position of the mouse and convert it to world coordinates.

Your sphere is not detecting collision because you never told it to do so. You told YOUR CAMERA to detect it.

Create a separated script and attach it to the sphere GO, and use OnCollisionStay rather than enter. Collision detection and mathematical movement (transform) doesn’t always work properly though, bear that in mind.

Good luck, and happy coding.

E.