If there is and object in front, execute this.

Note: This script is attached to the object behind and object in front.

I need to make it so when there is an object in front of another object, the object that is behind changes its boolean from false to true. Here is what I tried to do with a raycast:

function Update(){
var fwd = transform.TransformDirection (-Vector3.forward);
	if (Physics.Raycast (transform.position, fwd, 1)) {
    placedObject = true;
    }
}

Whats happening at the moment is that the placedObject variable is being set true for the object in front. I need it to be set true for the object behind. I have been trying to fix this for ages please help!

Just to re-iterate, if object is in front, do this to the object it is in front of.

This would be a good job for Dot Product : http://docs.unity3d.com/Documentation/ScriptReference/Vector3.Dot.html There is a demonstration video here : www.youtube.com/watch?v=JAAGdF-Wdas

–

1 Answer

1

You could use the version of Raycast:

That returns the RaycastHit object:

Then use the properties of that (collider or rigidbody or transform) to get the actual object that was hit. Then set the bool flag on that object.

Optionally I might use a collider for this, instead of casting a line/ray. For example, place an additional collider as a child of your object, and place that collider in the front of your object (so it always stays just in front of the object). Make it a Trigger, and then in the OnTrigger event you get a reference to the object it hit.