Debug.DrawRay line increases every frame

Hi everyone. I have an interesting problem. Debug.DrawRay / DrawLine increases in length each frame, thus passing through objects. But when it touches the real distance, it disappears. The problem is visual, but it is very annoying. Idk how to fix it.

private void Update()
    {
        if (isCollide(distance)) // check if collides with distance
        {
            // some code
        }
    }

    private bool isCollide(float distance) // raycast code
    {
        bool val = false;
        float castDist = distance;

        Vector2 endPos = castPoint.position * castDist;

        RaycastHit2D hit = Physics2D.Linecast(castPoint.position, endPos, 1 << LayerMask.NameToLayer("Penetrate"));

        if (hit.collider != null)
        {
            if (hit.collider.gameObject.CompareTag("Enemy"))
            {
                // my code
            }
        }
        else Debug.DrawRay(castPoint.position, endPos, Color.green); // that's line

        return val;
    }

AS the other comments have already said, this line doesn’t really make too much sense:

Vector2 endPos = castPoint.position * castDist;

castPoint.position is a position. You multiply the position by your distance value. So just for example, if distance is 5, the endpoint would be 5 times the distance of your start point from the world origin.

Depending on where the castPoint object is located, the resulting angle may be arbitrary.

Apart from all this you’re using a LInecast which expects two worldspace positions while you use DrawRay which expects a start position and a direction vector. So you should use DrawLine instead to actually match your line cast. Though I doubt that your linecast does what you want it to do. We just can’t infer from the provided code / description of your problem what you actually want to achieve. A raycast needs a direction in which the ray should be fired. A linecast needs to points in space and it essentially casts a ray from the starting point to the end point. So without knowing where that line / ray should go, we can’t tell you want to should use.

Usually you want to cast a ray into a certain direction. So for example the relative “forward” direction which in 2d physics is often times transform.right or Vector3.right.

So maybe you wanted to do:

Vector2 endPos = castPoint.position  + transform.right * castDist;

Keep in mind when using a layermask with only one layer, the ray / line cast will ignore all other geometry that is not on that layer. So even there may be geometry in the way that is on a different layer (default layer for example) it would pass through it and cound hit anything behind that geometry that is on your specified layer. So a layermask filters out all things that are not in the specified layers as if those objects don’t exist at all.