Hi guys!
I have the following problem:
The idea would be to have an item, in this case a small castle. Every time I click on the item, a speciifed number of soldiers will spawn around that mincastle. The thing is I want to keep clicking in the castle and spawning more soldiers, so I don’t want that to spawn again the soldiers in the position where there are already spawned soldiers.
I really suck at math, and I could find some code, but this one only reparts the soldier at an equal distance in the edge of the circle, and the spawn positions will be always the same.
Any tips about how to improve this code so I can keep spawn soldiers at new positions everytime and not being spawned in repeated positions? I know I have to check the position with Physics.overlap , but the thing is I don’t know how to spawn the soldiers in the edge of the radius randomly
I also tried with Random.insideCircle / Random.insideSphere but with those solutions the soldier spawned in the top of the castle… so Im a little lost
Here is a little sketch about the idea I have on mind and I will attach my current code
The current code
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Random = UnityEngine.Random;
public class ForgeSpawn : MonoBehaviour
{
public LayerMask layerGround;
private RaycastHit hit;
public GameObject soldierPrefab;
public int amountSoldiers;
public float radius;
private void Update()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 100, layerGround))
{
if (Input.GetKeyDown(KeyCode.Mouse0))
{
SpawnSoldiersAround(hit.transform.position);
}
}
}
private void SpawnSoldiersAround(Vector3 point)
{
bool incorrectSpawn = true;
for (int i = 0; i < amountSoldiers; i++)
{
/* Distance around the circle */
var radians = 2 * MathF.PI / amountSoldiers * i;
/* Get the vector direction */
var vertical = MathF.Sin(radians);
var horizontal = MathF.Cos(radians);
var spawnDir = new Vector3(horizontal, 0, vertical);
/* Get the spawn position */
var spawnPos = point + spawnDir * radius; // Radius is just the distance away from the point
/* Now spawn */
var soldier = Instantiate(soldierPrefab, spawnPos, Quaternion.identity) as GameObject;
/* Rotate the enemy to face the opposite direction of the castle */
soldier.transform.rotation = Quaternion.LookRotation(soldier.transform.position - transform.position);
/* Adjust height */
soldier.transform.Translate(new Vector3(0, soldier.transform.localScale.y / 2, 0));
}
}
}
I would appreciate any help… As Im a little frustrated with this