Placing an object in front of the camera

后端 未结 2 1199
陌清茗
陌清茗 2021-02-19 15:11

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

相关标签:
2条回答
  • 2021-02-19 15:38

    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 );
        }
    
    }
    
    0 讨论(0)
  • 2021-02-19 15:44

    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;
    }
    
    0 讨论(0)
提交回复
热议问题