Absinthe
Absinthe

Reputation: 3391

Find point at distance along a vector

Given a known direction and range I'm trying to calculate the 3D position along the vector at that range from the starting point.

To do this I'm basically following the Unity manual and the solution offered in various other questions about this topic:

Take your direction, normalise it and multiply by the required distance.

This isn't working for me but I can't figure out what's wrong. Here's my code that should draw a line from the starting point towards the mouse cursor position, ending at the given distance from the starting point:

IEnumerator DrawLineToMouse(float range)
{   
    RayCastHit hit;
    Vector3 endPos;
    float rangeSquared = Mathf.Sqrt(range);

    while (Input.GetButton("Fire1"))
    {
        if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, 2000))
        {
            endPos = (hit.point - startPos).normalized * rangeSquared; // startPos is the starting point of the line to be drawn  
            Debug.DrawLine(startPos, hit.point, Color.green, Time.deltaTime);
            Debug.DrawLine(startPos, endPos, Color.red, Time.deltaTime);   
        } 

        yield return null;
    }
}

For some reason the direction seems off. In this picture the green Debug.Draw line is direct from the starting point to the mouse position, the red line is to the calculated vector:

enter image description here

I've tried both perspective and orthographic cameras, and I've tried varying the starting point, the problem is the same. I don't know what to try regarding the code because everything I've read suggests it should work.

What could be the problem?

Upvotes: 2

Views: 2926

Answers (1)

derHugo
derHugo

Reputation: 90630

Currently your endPos is at the vector distance and direction but starting from 0,0,0

Instead it should rather be

endPos = startPos + (hit.point - startPos).normalized * rangeSquared;

or for better understanding

var distance = rangeSquared;
var direction = (hit.point - startPos).normalized;

endPos = startPos + direction * distance;

Upvotes: 4

Related Questions