# Spawn object at random position in front of player

I want to spawn cubes in front of the player at random positions in front of the player. So these positions should be constrained so the player is able to touch/interact with them. This works perfectly when facing the Z-axis, however the problem I’m having is that whenever I rotate the player looking at the X-axis. Then cubes are spawned on top of the player rather then having the depth offset. What do I have to do in order to generate cubes on random, constrained positions in front of the player?

``````    /**
* Calculate a random, constrained position in front of the player.
* Constraints:
* x: -1.0f & 1.0f from the player
* y: not below 0 or player height
* z: random depth from the player
*/
private Vector3 GetRandomPosition()
{
var player = PlayerManager.Instance.player.transform;
Debug.Log("Transform forward: " + player.transform.forward);

var spawnPos = player.position;
spawnPos.x += player.transform.right.x * Random.Range(-1.0f, 1.0f);
spawnPos.y = Random.Range(0.0f, 2.0f);
spawnPos.z += player.transform.forward.z * Random.Range(0.5f, 1.0f);

return spawnPos;
}
``````

At the moment I managed to fix my issue by calculating a random vector in world space and adding it to my forward offset:

``````/**
* Calculate a random, constrained position in front of the player.
* Constraints:
* x:
* y: not below 0 or player height
* z: Not
*/
private Vector3 GetRandomPosition()
{

var player = PlayerManager.Instance.player;
var distance  = 1.0f;
var tolerance = 0.5f;
var offset= player.transform.forward * distance;
var position = offset + new Vector3(Random.Range(-tolerance, tolerance), Random.Range(0f, 2.0f), Random.Range(-tolerance, tolerance));

return position;
}
``````