0
\$\begingroup\$

I'm trying to get a very basic "radar" system to work. Right now, I'm not even scanning, just looking at a known target location.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RadarScript : MonoBehaviour {

    public GameObject radar;
    public GameObject target;

    private bool found = false;

    void Update () {

        Vector3 lookLocation = target.transform.position - radar.transform.position;

        RaycastHit hitInfo;

        if (found == false) {

            Ray ray = new Ray (radar.transform.position, lookLocation);

            Debug.DrawRay (ray.origin, ray.direction, Color.red);

            if (Physics.Raycast (ray, out hitInfo, 10000.0f, 0)) {
                if (hitInfo.collider.tag == "Target") {

                    printHitInfo (hitInfo);

                    found = true;
                }
            }
        }
    }

    private void printHitInfo(RaycastHit hit) {
        Debug.Log ("TARGET FOUND!");
        Debug.Log ("Distance: " + hit.distance);
    }
}

So, here's the result can be seen here: https://gfycat.com/FloweryBraveCockroach

There's 2 problems here.

  1. The Debug.DrawRay call is only drawing the ray inside the cylinder (radar).
  2. The target is never being hit.

What's going wrong here ?

\$\endgroup\$
2
\$\begingroup\$

Direction is always a normalized vector. If you assign a vector of non unit length, it will be normalized. https://docs.unity3d.com/ScriptReference/Ray-direction.html

So Debug.DrawRay call is only drawing normalized vector.

Debug.DrawRay (ray.origin, ray.direction, Color.red);

this Is mean you used normalized vector Instead of self vector:

Debug.DrawRay (ray.origin,lookLocation.normalized, Color.red);

try this it should work:

Debug.DrawRay (ray.origin,lookLocation, Color.red);

enter image description here

Next problem:The target is never being hit.

because you used LayerMask in the last parameter

if (Physics.Raycast (ray, out hitInfo, 10000.0f, ⚠️0 (LayerMask)⚠️)

you can replace 0 by 1 it will work.but you don't need LayerMask here remove it like this:

if (Physics.Raycast (ray, out hitInfo, 10000.0f)
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.