Linecast not returning distance

I’ve got the following script that draws a line between two objects, one moveable (posChar) and one static (posFloor). I’m trying to use it to calculate the distance between these two objects, but the value of the float “distance” from the following code is always returning zero, regardless of where I move my character. Any advice on what I’m doing wrong would be appreciated. Thanks.

	public GameObject characterPos;
	public GameObject floorPos;

	Vector3 posChar;
	Vector3 posFloor;

	public float distance;


	void Update()
	{
		posChar = characterPos.transform.position;
		posFloor = floorPos.transform.position;

		Debug.DrawLine(posChar, posFloor);

		RaycastHit hit;
		
		if(Physics.Linecast(posChar, posFloor, out hit, LayerMask.NameToLayer("Ground")))
		{
			distance = hit.distance;
		}
		Debug.Log(distance);
	}

You need to use

if(Physics.Linecast(posChar, posFloor, out hit, 1 << LayerMask.NameToLayer("Ground")))

instead of

if(Physics.Linecast(posChar, posFloor, out hit, LayerMask.NameToLayer("Ground")))

If you just want the distance, why not use

Vector3.Distance(a,b)

?

Hi,

Physics.LineCast will tell you if a line drawn between the two points hits a collider, and if it does, the distance to that collider. I’m guessing one of two things is happening…

  • The Physics.LineCast is returning
    false, so distance is never being
    set, hence Debug.Log shows zero.
  • The Physics.LineCast is
    returning true because you’ve got
    a collider on the ground, which is
    intersecting with posFloor - hence
    the distance is genuinely zero.

If you just want the distance between two points, consider Vector3.Distance.

Hope this helps.