Home > front end >  How to spawn characters in certain area like a spawn point instead of inside circle
How to spawn characters in certain area like a spawn point instead of inside circle

Time:07-19

i'm working on a 2D game and i want to make characters spawn from the door to enter the store the script i have keeps spawning them in circle unit which is not what i want. i want them to spawn from the door then i will assign movements to them to walk around the store later. what should i do to achieve spawning them inside a area that i want like shown in this picture.

enter image description here

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CharacterSpawn : MonoBehaviour
{
    [SerializeField]
    private float spawnRadius = 7, time = 1.5f;

    public GameObject[] enemies;




    void Start()
    {
        StartCoroutine(SpawnAnEnemy());
    }

    IEnumerator SpawnAnEnemy()
    {
        Vector2 spawnPos = GameObject.Find("Bengal").transform.position;
        spawnPos  = Random.insideUnitCircle.normalized * spawnRadius;

        Instantiate(enemies[Random.Range(0, enemies.Length)], spawnPos, Quaternion.identity);
        yield return new WaitForSeconds(time);
        StartCoroutine(SpawnAnEnemy());
    }
}

CodePudding user response:

If you want to just spawn the characters at a specific point, you should be able to just remove the spawnPos = Random.insideUnitCircle.normalized * spawnRadius; line from the SpawnAnEnemy IEnumerator.

To spawn them randomly inside a rectangular area, I would use the Random.Range method instead of the unit circle. For example:

IEnumerator SpawnAnEnemy() {
    Vector2 spawnPos = GameObject.Find("Bengal").transform.position;

    Vector2 pointInRect = new Vector2(
        Random.Range(0, rectWidth),
        Random.Range(0, rectHeight)
        );
    spawnPos  = pointInRect;
    ...
}

CodePudding user response:

remove spawnPos = Random.insideUnitCircle.normalized * spawnRadius; from the IEnumerator. and if you want to move them around the area of the rectangle, just use

Create empty gameObject name it GameManager then assign this script to it

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameManager : MonoBehaviour
{

    public float moveSpeed = 1.0f;
    public Vector2 moveVector;

}

then assign ConstantMove to your characters. like this example:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CharacterConstantMove : MonoBehaviour
{

    GameManager Game_Manager;

    void Start()
    {

        GameObject gameController = GameObject.FindGameObjectWithTag("GameController");
        Game_Manager = gameController.GetComponent<GameManager>();

    }


    void Update()
    {

        transform.Translate(Game_Manager.moveVector * Game_Manager.moveSpeed * Time.deltaTime);
        
    }
}
  • Related