Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Placing an object in front of the camera

Tags:

unity3d

This should be an easy task, and I have googled it, but I can't figure out why any of the examples are working for me.

Basically, I want to place tiles on the ground in my first person game. I want the object I want to place on the ground to "float" in mid-air while choosing the perfect location for it. I can instantiate the object, make it a child of the player camera, but I'm unable to position it X units in front of the camera; it always ends up "on" the player;

public void StartPlacing ( Item item ) {
    Object itemPrefab = Resources.Load( "Prefabs/" + item.prefabName );

    GameObject itemObject = (GameObject)Instantiate( itemPrefab );
    itemObject.transform.parent = playerCamera.transform;

    // What to do here to place it in front of the camera? I've tried this:
    itemObject.localPosition = new Vector3( 0, 0, 5 );
}

UPDATE: The camera is a child of the player (Character Controller), and the camera is in perspective mode.

like image 338
toreau Avatar asked Mar 27 '14 18:03

toreau


2 Answers

You could use the forward vector of the object, something like this:

public GameObject frontObject;
public float distance;

void Update () {
    frontObject.transform.position = Camera.main.transform.position + Camera.main.transform.forward * distance;
}
like image 62
jparimaa Avatar answered Sep 23 '22 10:09

jparimaa


Thanks for all the useful suggestions, everyone! I came up with the following code which suits my needs:

using UnityEngine;
using System.Collections;

public class ConstructionController : MonoBehaviour {

    private Camera playerCamera;
    private GameObject itemObject;
    private float distance = 3.0f;

    // Use this for initialization
    void Start () {
        playerCamera = GetComponentInChildren<Camera>();
    }

    // Update is called once per frame
    void Update () {

        if ( itemObject != null ) {
            itemObject.transform.position = playerCamera.transform.position + playerCamera.transform.forward * distance;
            itemObject.transform.rotation = new Quaternion( 0.0f, playerCamera.transform.rotation.y, 0.0f, playerCamera.transform.rotation.w );
        }

    }

    // Start constructing an item
    public void StartConstructingItem ( Item item ) {
        Object itemPrefab = Resources.Load( "Prefabs/" + item.prefabName );

        itemObject = (GameObject)Instantiate( itemPrefab );
    }

}
like image 29
toreau Avatar answered Sep 26 '22 10:09

toreau