I have this script that should turn an object when it approaches to another:
function Update () {
var mainRay = new Ray(transform.position, transform.TransformDirection(Vector3.forward));
var mainHit : RaycastHit;
var sight = 10.0;
if (collider.Raycast(mainRay,mainHit,sight)) Turn();
else transform.Translate(Vector3.forward*speed*Time.deltaTime);
}
For some reason it doesn’t work and the Turn() function is never called. I don’t want to use Physics.Raycast, because I don’t want my character hitting corners or such things.
What am I doing wrong?
The Collider.Raycast() method casts a ray that will be true only if the ray hits THIS collider. The Physics.Raycast() method will cast a ray that will be true if it hits ANY collider. In your code fragment, I am assuming that you wish to cast a ray from the current game object outwards in some direction. As such, Physics.Raycast() is what you want. Using Collider.Raycast() will never be true as (if I am understanding correctly) you are always casting out from the game object trying to hit the collider which is yourself.
Hmmm the code compiles OK with that “Turn()” without ‘;’ at the end? Here I use Physics.raycast instead of the collider one and it works well. I don’t know well the difference between they, but you can try this one.
if( Physics.Raycast( origin, direction, raycastHitObject, rayDistance ) )
{ /* ray collision detected */ }