Enemy spawn script does not spawn in circle as intended
I found a script online for my game, where enemies spawn in a circle around the player. I tweeked it a bit so the distance from the player they spawn, is random. Here is the script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnEnemy : MonoBehaviour
{
public GameObject enemy;
public int randomNr;
void Update ()
{
randomNr = Random.Range(0, 200);
if (randomNr == 1)
{
Spawn();
}
}
void Spawn ()
{
float r = Random.Range(5, 15);
float angle = Random.Range(0, Mathf.PI * 2);
Vector2 pos2d = new Vector2(Mathf.Sin(angle) * r, Mathf.Cos(angle) * r);
Instantiate(enemy, pos2d, Quaternion.identity);
}
}
I have assigned the script to the player, so wherever he is, they spawn around his positon. The problem is, they don't. Apparently they spawn around one static position, which makes sense i guess, since the player transform isn't a part of the equation.
In the two pictures you see two different positions of the player. In one of the pictures i moved the player before pressing play, and they still spawn around the same position.
I never really looked into Mathf, so i have no idea what to do. I already spend some time trying to fix it, but without luck. I would spend more time, but since i am entering ludum dare, i dont have much time.
So in conclusion: I want the enemies to spawn in a random distance from the player, wherever he is. Not just spawning the enemies in a distance from the same static position.
I hope someone can help! :-)
Answer by NinjaRubberBand · Apr 19, 2020 at 04:06 PM
Okay so i fixed it myself right after posting this hehe. The simple solution is instead of writing
Vector2 pos2d = new Vector2(Mathf.Sin(angle) r, Mathf.Cos(angle) r);
You write: Vector2 pos2d = new Vector2(transform.position.x + Mathf.Sin(angle) r, transform.position.y +Mathf.Cos(angle) r);
Your answer
Follow this Question
Related Questions
Problems with instantiated objects in a circle formation 0 Answers
Clamping a value between two radiuses 1 Answer
Flag capture with spawning and destroying gameObject 0 Answers
[C#] Only one instantiate object is working, the rest is not.. Help meee 0 Answers
Unet: Spawn bullet - client does not have a reference of bullet 1 Answer