这应该是一项简单的任务,我已经用Google搜索了,但我无法弄清楚为什么任何一个例子都适合我。
基本上,我想在我的第一人称游戏中将瓷砖放在地上。我希望我想放置在地面上的物体在空中“漂浮”,同时选择它的完美位置。我可以实例化该对象,使其成为玩家相机的孩子,但我无法将X单位定位在相机前;它总是最终“在”玩家身上;
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 );
}
更新:相机是播放器(角色控制器)的孩子,相机处于透视模式。
答案 0 :(得分:13)
您可以使用对象的forward vector,如下所示:
public GameObject frontObject;
public float distance;
void Update () {
frontObject.transform.position = Camera.main.transform.position + Camera.main.transform.forward * distance;
}
答案 1 :(得分:4)
感谢所有有用的建议,大家!我提出了以下适合我需要的代码:
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 );
}
}