Search code examples
unity-game-enginegame-physics

find nearest player to line [Unity3D]


I Want to find nearest player to line, to be more specifict I have target indiator in center of screen, and imagine theres a line between my character and that target indicator, I will attach image to be more clear, if target indocator is not exacly on other player i want to get nearest player from that line to take a damage. I can't find any solution, I Hope I explained it clearly,

enter image description here


Solution

  • You can use the unity's Ray class, which is the math equivalent to a line. Find below two useful functions you can use, to calculate the distance with a cross product, and then find the nearest with the square distance, instead of the distance for the sake if efficiency.
    Square roots are not efficient computation wise so its preferable to avoid them. For this case makes sense as you need the shortest distance, so you can use the .sqrMagnitude. If you need the distance itself, then you would use .magnitude (distance itself). However if you are not going to use the square root, or the .magnitude in an Update() its not a bug deal).

    public float DistancePointToLineSqr(Ray ray, Vector3 point) {
        return Vector3.Cross(ray.direction, point - ray.origin).sqrMagnitude;
    }
    
    private Vector3 GetClosestToLinePoint(List<Vector3 points>) {
        Ray vertical = new Ray(transform.position, Vector3.up);
        Vector3 closestPoint = points.OrderBy(point => DistancePointToLineSqr(vertical, point)).FirstOrDefault();
    
        return closestPoint;
    }
    

    For your line, as you mention a target indicator, you might find Camera.ScreenPointToRay useful.