将物体放置在相机前面 [英] Placing an object in front of the camera
问题描述
这应该是一件容易的事,我已经在Google上进行了搜索,但是我不知道为什么这些示例对我有用.
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.
基本上,我想在第一人称游戏中将瓷砖放置在地面上.我希望将要放置在地面上的物体悬空"在空中,同时为其选择最佳位置.我可以实例化该对象,使其成为播放器相机的子代,但无法将其放置在相机前面X个单位;它总是以在"播放器上结尾;
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.
推荐答案
谢谢大家的有用建议!我想出了适合我需要的以下代码:
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 );
}
}
这篇关于将物体放置在相机前面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!