unity-game-enginecamerahololens

Can you move an object in unity by maintaining a standard distance from the camera?


I'm a newbie unity user and I'm working on a Basket shoot simulator in Hololens2. Right now I'm working on a button that, when pressed should move the hoop where the camera is looking but it needs to have the Pos Y = 3 and be 4,5 meters away from the camera (since those are the measures in meters for a free throw in basketball).

I've tried to use camera.transform.forward but in no way I was able to set the free throw distances that i need from the camera, especially the Y. The method was this:

public GameObject hoop;
public new GameObject camera;

float freeThrowY = 3;
float freeThrowZ = (float) 4.5;

public void ChangeHoop ()
{
    hoop.transform.position = transform.position + camera.transform.forward * freeThrowY * freeThrowZ;
}

and the hoop was very far obviously, so I tried doing this:

hoop.transform.position = camera.transform.forward + new Vector3(camera.transform.position.x, freeThrowY, freeThrowZ); 

But the hoop just stays in basically the same position, changing from around 0 to 1 meters. (The hoop does move, so the button works)

I also tried:

hoop.transform.position = new Vector3(camera.transform.forward.x, camera.transform.forward.y + freeThrowY, camera.transform.forward.z + freeThrowZ);

But same problem as before.

I've searched for 2 days online but none of the solutions worked for me, so I guess I'm missing something probably very simple.

Thank you for helping (sorry for the english, if something is not clear I'll try to explain it better)


Solution

  • First you need to get the cameras forward vector without any x/z rotation.
    Once that forward vector is aligned with the ground plane, you can multiply it by "distanceAway".

    var forward = Vector3.Cross(camera.transform.right, Vector3.up);
    var position = transform.position + forward * distanceAway;
    

    Then set the positions y component to your "distanceUp" value, and assign the final position to your hoop.

    position.y = distanceUp;
    
    hoop.transform.position = position;