//spawn a new enemy
    public void spawnNew(Vector3 position, GameObject unit)
    {
        //store the raycast hit
        Vector3    pos = position;
        RaycastHit hit;
        bool       isInstantiated = false;

        for (int i = 0; i < 6; i++)
        {
            if (Physics.Raycast(pos, -Vector3.up, out hit))
            {
                Debug.Log($"Spawn Point:{hit.point}/{hit.collider.gameObject.tag}");
                if (hit.collider.gameObject.CompareTag("Battle ground"))
                {
                    //if the raycast hits a terrain, spawn a unit at the hit point
                    GameObject newUnit = Instantiate(unit, hit.point, Quaternion.Euler(0, 90, 0));
                    inspector.addFrom(newUnit);
                    isInstantiated = true;
                    break;
                }
                else
                {
                    int sign  = rnd.Next(0, 2) * 2 - 1;
                    int sign2 = rnd.Next(0, 2) * 2 - 1;
                    pos.x += 2.4f * sign;
                    pos.z += 2.4f * sign2;
                }
            }
        }
        if (!isInstantiated)
        {
            Debug.LogError("Couldn't instantiated enemy");
        }
    }
Exemple #2
0
    public bool placeUnit(Vector3 center, Vector3 size, GameObject unit)
    {
        bool       isInstantiated = false;
        RaycastHit hit;
        Vector3    pos        = area.getRandomPosition(center, size);
        int        maxattempt = 10;

        for (int i = 0; i < maxattempt; i++)
        {
            if (Physics.Raycast(pos, -Vector3.up, out hit))
            {
                if (hit.collider.gameObject.CompareTag("Battle ground"))
                {
                    //if the raycast hits a terrain, spawn a unit at the hit point
                    GameObject newUnit = Instantiate(unit, hit.point, Quaternion.identity);
                    updateRotation(newUnit);
                    newUnit.SetActive(false);
                    inspector.addFrom(newUnit);
                    isInstantiated = true;
                    break;
                }
                else
                {
                    Debug.LogWarning($"{i} attempted SAFECHECK {unit.tag} {unit.name} didn't spawn / {pos} -> {hit.collider.gameObject.tag} {hit.collider.gameObject.name}");
                    pos = area.getRandomPosition(center, size);
                }
            }
            else
            {
                Debug.LogWarning($"{i} attempted SAFECHECK {unit.tag} {unit.name} didn't spawn {pos} -> didn't collide anything (out of boundary)");
                pos = area.getRandomPosition(center, size);
            }
        }
        if (!isInstantiated)
        {
            Debug.LogError($"Couldn't instantiated agent after {maxattempt} attempt -> {unit.tag} {unit.name}");
        }
        return(isInstantiated);
    }