Linecast doesn't work?

I have such a code:

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

public class LookingPlayer : MonoBehaviour {

    public GameObject Player;
    // Use this for initialization
    void Start () {
       
    }
   
    // Update is called once per frame
    void Update () {
        if (Physics.Linecast(this.transform.position, Player.transform.position))
            Debug.Log("blocked");
   
        Debug.DrawLine (this.transform.position, Player.transform.position);
    }
}

The line is drawn just fine, but the funcion Linecast() doesn’t return false.

Each object has a BoxCollider2d, so I can’t understand why linecast doesn’t return false, since there is an obstacle(black wall) between two objects

You want “Physics2D.Linecast”. 3D physics and 2D physics don’t detect each other or interact.

1 Like

Ok, it works now, but it returns true even when nothing is between player and an object.

Ah yes, that is because LineCast doesn’t return a boolean, it returns a RaycastHit2D object with information about what was hit. By doing if(linecast) you’re checking if it has results, which is always true. Try assigning that linecast to a new local RaycastHit2D variable, and checking what was hit.

https://docs.unity3d.com/ScriptReference/Physics2D.Linecast.html
https://docs.unity3d.com/ScriptReference/RaycastHit2D.html