Physics.RayCast - Am I doing this correctly.

Hi. I have a set of cubes which have a BoxCollider and Rigidbody attached. I want to cast a ray in the cubes onStart() to see if it is hitting a GreyCube next to it and if it is to disable it being able to move. Am I doing this correctly?

Here is the code I have in Start ():

    void Start()
    {
        thrust = 7f;
        gravity = 11.5f;
        direction = GameObject.Find("gGameController").GetComponent<CubeScript>().direction;
        if (direction == "left")
        {
            if (Physics.Raycast(transform.position, new Vector3(transform.position.x - 2, transform.position.y, transform.position.z), out ray))
            {
                if (ray.collider.tag == "tGreyCube")
                {
                    hasStopped = true;
                    Debug.Log("hit");
                }
            }
        }
       
        pos = transform.position;
    }

Well do you get ‘hit’ debugged in your console, if yes then your question is answered

If it’s not working now, then try logging ray.collider.gameObject.name and see what you get.

I’d bet you get the cube doing the raycast’s name there. You’re raycasting from the center of the cube, which is like shooting a gun from inside your stomach - you’re gonna hit yourself first. The best thing to do would probably be to put the grey cube on a specific layer, and raycast using a mask for that layer. That way you’ll only hit the one object you’re seeking, even if other objects (like yourself) are in between.

I don’t, which is why I posted.

Now that sounds like it may be where I should be heading to solve this. I’ll get on to it and report back.

Thanks!

Hmmm! This all worked perfectly when I removed the code and put it in Update. It seem Start() was having an issue processing the physics code.

1 Like

Have a shot in awake, again I’m not sure since I don’t really use raycasts and physics :frowning:

Nope, same as having it in Start().

It should work in Start, my guess would be unity can’t find the GameObject soon enough or something. Try putting Debug.Log() Statements in each if statement, see where the problem is! Do this in the Start()

An option, if you only wanted the raycast to be shot once, is to do something like this:

public bool RayShot = false;

void Update()
{
    if(!RayShot)
         if (direction == "left")
            {
                if (Physics.Raycast(transform.position, new Vector3(transform.position.x - 2, transform.position.y, transform.position.z), out ray))
                {
                    if (ray.collider.tag == "tGreyCube")
                    {
                        hasStopped = true;
                        Debug.Log("hit");
                    }
                }
            }
         RayShot = true;
    }
}