Raycast does not get anything.

HI
So i tried to get gameobject in the scene using a raycast.
Here is the code:

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

public class WaypointController : MonoBehaviour
{
    public GameObject[] neighbours;
    public List<GameObject> viewingNeighbours;
    RaycastHit hitInitialise;
    public List<GameObject> pNeighbours;
    void Start()
    {
        neighbours = GameObject.FindGameObjectsWithTag("Waypoint");
        for (int i = 0; i < neighbours.Length; i++)
        {
            pNeighbours.Add(neighbours[i]);
        }
        for (int i = 0; i < pNeighbours.Count; i++)
        {
            Debug.DrawLine(transform.position, pNeighbours[i].transform.position, Color.blue, 2000);
            if (Physics.Raycast(transform.position, pNeighbours[i].transform.position, out hitInitialise, 2000))
            {
                viewingNeighbours.Add(hitInitialise.collider.gameObject);
            }
        }  
    }
}

In the scene (picture) we can clearely see the blue lines going trough the colliders of the other capsules.
But… The list viewingNeighbourg does not get anything, stills empty.
I am assuming raycast neither, it deos not get anything neither.
What did i done wrong?
Thanks for help. :slight_smile:

6209492--682214--capsuleraycast.PNG

Sorry, I have not tried to replicate this so I’m not certain, but it appears you are using a transform position as the direction of the ray cast. This will only work if your ray origin is at 0,0,0. You probably want to subtract the origin of the ray from the transform position to give you a direction vector from the origin of the ray to the target position. I hope that helps.

2 Likes

Right.
An alternative, depending on the use case, would be to use a Linecast instead. Unlike a Raycast a Linecast takes two end points of the line you want to check. It’s an easy solution when you want to cast a ray between two points.

Rays, by definition, have a start / origin, a direction and are of infinite length. A raycast can be limited to a certain distance though. A Linecast is always a limited line since it’s defined by the two endpoints.

2 Likes

So i have done tips you told me, and both are working very good.
Just notice due to the event case they are not really the same.
Thank both of you. :slight_smile:

1 Like