- Home /
overlapping of enemy
hi there, i have script that has 2 public array variables called spawnPoints and spawnObjects, i have 9 spawnPoints and 4 spawnObjects. These 4 spawnObjects are placed on 4 spawnPoints. Here what i am doing is whenever i press the mouse button i m changing the position of spawnObjects to other spawnPoints, its working fine but the spawnObjects are overlapping some times.
please can anyone rewrite this code
using UnityEngine;
using System.Collections;
public class Forward : MonoBehaviour
{
public GameObject[] spawnPoint;
private GameObject spawn;
public GameObject[] spawnObjects;
private GameObject objectSpawn;
void Update ()
{
if (Input.GetMouseButtonDown (0)) {
int a = Random.Range (0, spawnPoint.Length);
int b = Random.Range (0, spawnObjects.Length);
spawn = spawnPoint [a];
objectSpawn = spawnObjects [b];
objectSpawn.transform.position = spawn.transform.position;
}
}
}
Answer by LawgiverSS2 · Jul 30, 2015 at 05:00 AM
To avoid duplicate random values, generate a random sequence between 0 and spawnPoints.Length (exclusive).
Use a shuffle algorithm such as Fisher Yates to generate your sequences:
for (int i = length - 1; i > 0; i--)
{
int j = random.Next(i + 1);
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
Answer by NeverHopeless · Jul 30, 2015 at 06:48 AM
A possibility to fix this problem is to take an array for currently available positions for spawining, say AllowedPositions
.
So, when the game starts:
AllowedPositions = new int[] { 0,1,2,3,4,5,6,7,8 }
Now run:
int a = Random.Range (0, AllowedPositions.Length)
and pick ath element from AllowedPositions
and remove it from the array.
int randomAvailablePosition = AllowedPositions[a];
e.g., Random.Range
returns 3
, then:
AllowedPositions = new int[] { 0,1,2, 4,5,6,7,8 }
Since 3
is not in the AllowedPositions
array so you can not pick this position again and overlapping will not occur.
A better option is to use List<T>
since manipulation would be easy.
Your answer
Follow this Question
Related Questions
How to make different animations affect different parts of the object? 2 Answers
Using a transparent shader and I'm getting graphical glitches with textures overlapping each other 1 Answer
Overlapping sprites in Unity2D 1 Answer
check box overlap / colliders in edit mode 0 Answers
Grab and drag object in physical and realistic way 2 Answers