Muhammad Faizan Khan
Muhammad Faizan Khan

Reputation: 10561

Get position from player forward at constant distance

The simple way to get player front position at specific distance

     Vectro3 forward = player.transform.forward * distance;
     Vector3 newPlayerFronPosition= player.transform.position + new Vector3(forward.x, forward.y, forward.z);
     newPlayerFronPosition= new Vector3(newPlayerFronPosition.x, newPlayerFronPosition.y - 4f, newPlayerFronPosition.z);
     navigationCanvas.transform.position = newPlayerFronPosition;
     navigationCanvas.transform.rotation = camRotationToWatch.transform.rotation;

its actually working fine but the problem is as my player move up or down the navCanvas become appear ver near to my player. How to mainitain spcific distance all the time.?? that no matter player look above or down the navcanvas display at specfic distance.(position)

disatnceUICam = Vector3.Distance(newPlayerFronPosition, player.transform.position);

I also logged the distance and surprisingly it the distance is changing when i am moving up or down. its changing from 6 to 12 as i am looking up to down.

Upvotes: 0

Views: 819

Answers (1)

Fehr
Fehr

Reputation: 544

If I've understood you correctly, and you want a point on in front of your player transform on the X Z Plane a set distance from the forward of your player, you should try something like this:

    Vector3 horizontalForward = new Vector3(
        player.transform.position.x + player.transform.forward.x,
        player.transform.position.y,
        player.transform.position.z + player.transform.forward.z
    ).normalized * distance;

I suspect what you're describing is occurring because the transform of your 'player' variable is connected to the direction of your game camera. As the camera looks up, the world position of your forward changes relative to the camera. Using just the X and Z will produce a varying distance as your camera transform rotates around the X Axis. Perhaps this diagram will illustrate what I mean a little better:

effect of y vector

Sorry the hypotenuse is a little wonky but you get the idea right?

Upvotes: 1

Related Questions