FPS instantiate objects

I’m trying to make a game where you create objects when you press the mouse button.

I’ve followed the tutorial on 3Dbuzz and they helped me fix that prefabs spawn in the game everytime I press the mousebutton.

but the tutorial dealt with a simple 2D shooter, so the spawn position of the prefabs are pretty dull: they spawn in a fixed X position and the player is using the FPS script.

I want the objects to spawn where the player looks, both X and Y positions.

here’s the code:

using UnityEngine;
using System.Collections;

public class playerscript : MonoBehaviour {
	
	public GameObject cubeprefab;
//Vector3 originalposition;
//Quaternion originalrotation;

// Use this for initialization
void Start () {
	
	//if(transform.position != null)
	//{
	//transform.position = originalposition;
	//transform.rotation = originalrotation;
	
	
	//}

}

// Update is called once per frame
void Update () {
	
	
	if(Input.GetKeyDown("e"))
	{
	//originalposition = transform.position;
	//originalrotation = transform.rotation;	
	Application.LoadLevel("the cave");	
		
	}
	
	if(Input.GetKeyDown("mouse 1"))
	{
	Vector3 position = new Vector3(transform.position.x, transform.position.y + transform.localScale.y / 2);	
	Instantiate(cubeprefab, position, transform.rotation);	
		
	}
	
	
	

}


void Reset () {
	

}

}

1 Answer

1

add a public variable gameobject named camera;
then on your fps character thing add the childed camera gameobject to this public variable.
then replace your mouse 1 code with this

if(Input.GetKeyDown("mouse 1")) {

Instantiate(cubeprefab, camera.transform.position, camera.transform.rotation); 

}

this will make your cube prefab pop straight out of where the camera is, unless your camera is in the player collider, in that case you have to use physics.ignorecollision for the cubeprefab and the fps thingy

you can spawn them infront of it but you have to make another empty gameobject for it to spawn from. just put physics.ignorecollision(cubeprefab.collider, collider) under your instantiated cube

–

happy days ;D

–