- Home /
Instantiate object in front of player?
Hi there!
I'm trying to instantiate a prefab in front of the player. What I currently have looks like this:
if(Input.GetKeyDown(KeyCode.E))
{
Instantiate(meleePrefab, new Vector3(0,0 +2), transform.rotation);
}
It's supposed to be placed 2 units in front of the player's current position. But this will place the object in the world position of 0,0,2.
How do I make it find the players current position and then place it 2 units in the z-axis from the players position?
Thanks!
Answer by Jeff-Kesselman · Jul 12, 2014 at 11:54 PM
if(Input.GetKeyDown(KeyCode.E))
{
Instantiate(meleePrefab, transform.position+(transform.forward*2), transform.rotation);
}
thanks for that answer, super simple but couldn't quite figure it out.
Answer by SuleimanAbdulla · Jun 30, 2021 at 12:43 PM
if you want to use new vector 3 to spawn object in front of your player transfom.position enable the object to spawn at player position no matter the player goes by adding new vector three you define far the object to spawn at player position by specify the coordinate xyz and Quaternin.identity if you want you object to spawn at default rotation use Quaternion.identity
if(Input.GetKeyDown(KeyCode.E))
{
Instantiate(meleePrefab,transform.position + new Vector3(0,0 +2,0),Quaternion.identity);
}
Your answer
Follow this Question
Related Questions
Updating transform.position correctly to instantiated GameObjects 0 Answers
The instantiated prefab doesn't fire correctly from the player 2 Answers
transform.position on Instaniated object does not match inspector 0 Answers
How to carry over variable (transform.position) and use it as Vector3 for instanitating a prefab 2 Answers
How can I naming each instantiated object in "for" loop ? 1 Answer