Unity: detect if path is clear using Raycast

Currently my code looks like this:

    Vector3 tempPos = transform.position;
    Vector3 checkPos = new Vector3(tempPos.x, tempPos.y, Mathf.Round(tempPos.z + 1));
    if (Input.GetKey(KeyCode.W))
    {
        Vector3 direction = checkPos - transform.position;
        Ray ray = new Ray(transform.position, direction);
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit))
        {
            Debug.Log(hit.point);
        }
        Debug.DrawRay(transform.position, direction, Color.black, 20, false);
    }

however even when i am right up against an object, I get nothing from my Debug.Log() statement. As a matter of fact, I cannot even call a Debug.DrawRay() statement as it doesn’t show anything either. What on Earth could I be doing wrong? Any help would be appreciated. Thanks in advance!

1

Answers


  1. thoxey
    0 Votes

    Hard to know the problem from a small snippet but you could try:

    Vector3 fwd = tempPos.transform.TransformDirection(Vector3.forward);
    if (Physics.Raycast(raycastObject.transform.position, fwd, out objectHit, 50))
    {
        Debug.Log("Hit");
    }
    
Please signup or login to answer this question.

Signup for an account and start participating in our site today!




Social Signup

You can also login with your Facebook, Twitter or Linkedin account

Log in with Facebook