- Home /
Spawn object in front of player and the way he is facing?
Hey, how could I instantiate an object in front of the player AND the way he is facing? I've got this but it only spawns the object X amount units from the player on the x axis.
playerPos = player.transform.position;
spawnPos = new Vector3(playerPos.x+10, playerPos.y, playerPos.z);
Instantiate(Resources.Load(iconDragging.GetComponent<UISprite>().spriteName), spawnPos, Quaternion.identity);
Answer by PlasmaByte · Aug 16, 2014 at 11:51 PM
You can use the player.transform.forward direction to get the players direction as a vector and transform.rotation to get the orientation. You can also do math operations of vectors which makes things so much neater than modifying the components.
Vector3 playerPos = player.transform.position;
Vector3 playerDirection = player.transform.forward;
Quaternion playerRotation = player.transform.rotation;
float spawnDistance = 10;
Vector3 spawnPos = playerPos + playerDirection*spawnDistance;
Instantiate(Resources.Load(iconDragging.GetComponent<UISprite>().spriteName), spawnPos, playerRotation );
I have been struggling with creating a dash controller to move forward based on the camera's position along with the camera's forward facing direction and this has helped me alot. Thanks!
Answer by Tassos24 · Jun 15, 2018 at 01:08 PM
One quick question on that. the spawnPos must get new values in Update() function I suppose? not at Start()? or in both of them?
You could initiate spawnPos in Start(), but the only advantage I see would be to allow the desired behavior, here shooting, on the very first frame. I don't think it would hurt either way.
Your answer
![](https://koobas.hobune.stream/wayback/20220613160753im_/https://answers.unity.com/themes/thub/images/avi.jpg)