- Home /
How to instantiate a prefab in front of FPS camera?
Hi, currently building a project that required a cube or block to be spawn in front of the player like the Minecraft thing using FPS camera. Now I only able to spawn exactly the position of the camera which the player will stuck in the middle of the cube, I wanted it to be spawn slightly in front of where the camera is facing. Thank you.
var creation : Transform;
function Update () {
if(Input.GetButtonDown("Fire1"))
Instantiate(creation, Vector3(transform.position.x, transform.position.y, transform.position.z), transform.rotation);
}
Answer by Eric5h5 · Nov 23, 2012 at 10:12 PM
Use transform.forward, where "distance" is the desired number of units in front:
Instantiate(creation, transform.position + transform.forward*distance, transform.rotation);
Answer by greatestprez · Nov 23, 2012 at 10:09 PM
Create a new empty game object, name it "pos", make it a child object of your main camera, reset it's position, and then set its z-position to 3. (make sure you do steps in this order) Then alter your script to say this:
var creation : Transform;
function Update () {
if(Input.GetButtonDown("Fire1"))
Instantiate(creation, transform.FindChild("pos").position, transform.FindChild("pos").rotation);
}
Answer by laradov · Nov 24, 2012 at 12:33 AM
Try this:
private GameObject objCamera;
private Vector3 SpawnPosition;
private int DistanceToCamera = 5;
public Transform creation;
void Start () {
objCamera = (GameObject) GameObject.FindWithTag("MainCamera");
}
void Update () {
if(Input.GetButtonDown("Fire1")) {
SpawnPosition = objCamera.transform.forward * DistanceToCamera + objCamera.transform.position ;
Instantiate(creation, SpawnPosition, Quaternion.identity);
}
}
Your answer
Follow this Question
Related Questions
Which is better, shooting a bullet from camera or from the gun itself? 3 Answers
Checking if object intersects? 1 Answer
Multiplying GUIs 0 Answers
Lerping Field Of View is buggy 1 Answer