- Home /
Place a object in front the camera in the coordinate 0 of Y axis
Hi, I need help with this script:
public GameObject itemObject;
public float distance = 3.0f;
public Transform cameraTransform = Camera.main.transform;
public void OnPointerDown(PointerEventData eventData)
{
Instantiate(itemObject, cameraTransform.position + cameraTransform.forward * distance, Quaternion.identity);
Debug.Log("Was Pointed");
}
This script place a object in front the camera with 3m of distance, but I want that the object always be in the coordinate 0 of the Y axis, even if I look up or down.
Thank you.
Answer by Perfecter · Jul 05, 2018 at 09:16 PM
Hi! Try this:
public GameObject itemObject;
public float distance = 3.0f;
public Transform cameraTransform = Camera.main.transform;
public void OnPointerDown(PointerEventData eventData)
{
var newObject = Instantiate(itemObject, cameraTransform.position + cameraTransform.forward * distance, Quaternion.identity);
newObject.transform.position = new Vector3(newObject.transform.position.x, 0, newObject.transform.position.z);
Debug.Log("Was Pointed");
}
Oh thank you so much, it works perfectly, but I saw a issue, in the line: newObject.position
it should be newObject.transform.position
right?
Answer by tormentoarmagedoom · Jul 04, 2018 at 10:20 PM
Good day.
Best way is to make the object child of the camera object. So the coordinate of position is very easy to find, and the camera can be lloking anywhere.
So do somethig like this:
GameObject NewItem= Instantiate(itemObject, cameraTransform);
NewItem.transfomr.LocalPosition = *The Position relative to the cam*
Bye!
Hi tormento, thanks for answer, I modified the script but it didn't work :/ even it does the same as my script.