(2D) Instantiating in front with offset
Hey
In front of my moving player GameObject (rigidbody2D) another GameObject shall be instantiated. But it should not collide with my player. This always means +-0.7 to +-2 units next to it. Here is my approach:
Vector3 spawnPos = (player.transform.position + player.transform.forward) * spawnDistance;
Vector3 playerWay = spawnPos;
float distance = Vector2.Distance(spawnPos, playerWay);
while ((distance < 0.7f) && (distance ) > 2f))
{
spawnPos.x = Random.Range(spawnPos.x - 2f, spawnPos.x + 2f);
spawnPos.y = Random.Range(spawnPos.y - 2f, spawnPos.y + 2f);
distance = Vector2.Distance(spawnPos, playerWay);
}
Instantiate(enemy, spawnPos, Quaternion.identity, transform);
I think my approach with x and y is not correct. It may only move the spawn point to the left and right.
Answer by Hellium · May 08, 2019 at 10:57 AM
float minDistance = 0.7f;
float maxDistance = 2f;
float distance = Random.Range( minDistance, maxDistance );
if( Random.value < 0.5f ) distance = -distance;
Vector3 spawnPos = (player.transform.position + player.transform.up) * spawnDistance + player.transform.right * distance;
Instantiate(enemy, spawnPos, Quaternion.identity, transform);
This drawing would have been very useful in your original question.
I've update my answer, give it a try.
@Hellium All right, we're getting closer to the solution. If this was not yet understandable, the player can move in any direction from (2D). I tried to replace the .up with .forward in your solution. But the spawnPos is sometimes out of my range.
Sketches correction:
What does not work with the provided solution?
If you want the enemies to be spawn on the same "axis" (only on the Y axis for instance, regardless of the player rotation, but aligned with player position), try
Vector3 spawnPos = (player.transform.position + Vector3.up) * spawnDistance + Vector3.right * distance;