- Home /
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;
}
You have a local and global space when you rotate an object its local rotational axis get offset from the global ones.
Just make sure you are using the correct coordinate space/ transform when you are spawning items.
hi @sacredgeometry Thanks for your reply. Can you give some more information on how I would do that. At the moment I've fixed it by creating a random offset from my forward direction. See my answer below.
Answer by AnScience · Feb 10, 2020 at 10:28 AM
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;
}
Your answer
Follow this Question
Related Questions
Vector3 not receiving coordinates 1 Answer
Circle inside Circle 1 Answer
Randomly position Instantiated GameObject's 1 Answer
Vector3.Lerp moves other characters over network to (0, 0, 0) 1 Answer
spawn muzzle flash with random rotation? 2 Answers