Limit weapon range by line of sight

I thought it was weird that the weapon range didnt take into account LOS and allowed you to see the range go through walls, even tho the shoot action cannot take those shots ever.

I did this by adding a final validation check on ShowGridPositionRange() in GridSystemVisual.

Remember to add the reference to the layer mask and assign this in editor

[SerializeField] private LayerMask obstaclesLayerMask;

Vector3 unitWorldPosition = LevelGrid.Instance.GetWorldPosition(gridPosition);
                Vector3 testWorldPosition = LevelGrid.Instance.GetWorldPosition(testGridPosition);

                Vector3 aimDir = (testWorldPosition - unitWorldPosition).normalized;
                
                float unitShoulderHeight = 1.7f;
                if (Physics.Raycast(
                        unitWorldPosition + Vector3.up *unitShoulderHeight,
                        aimDir,
                        Vector3.Distance(unitWorldPosition, testWorldPosition),
                        obstaclesLayerMask))
                    {
                        //line of sight blocked by obstacle
                        continue;
                    }
3 Likes

Thinking about it more my line of sight is going from the players shoulder height down to the 0y on each tile, so possibly the LOS will get blocked on low cover when it shouldn’t. So I rewrote it so it checks at shoulder height on each tile so the LOS should be a horizontal raycast and never be blocked by low cover.

float unitShoulderHeight = 1.7f;
                Vector3 unitWorldPosition = LevelGrid.Instance.GetWorldPosition(gridPosition) + Vector3.up *unitShoulderHeight;
                Vector3 testWorldPosition = LevelGrid.Instance.GetWorldPosition(testGridPosition) + Vector3.up *unitShoulderHeight;

                Vector3 aimDir = (testWorldPosition - unitWorldPosition).normalized;
                
                if (Physics.Raycast(
                        unitWorldPosition,
                        aimDir,
                        Vector3.Distance(unitWorldPosition, testWorldPosition),
                        obstaclesLayerMask))
                    {
                        //line of sight blocked by obstacle
                        continue;
                    }
3 Likes

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.

Privacy & Terms