简体   繁体   中英

Spawning zombies just outside of camera bounds in Unity

Usually in any new engine I try to make a top down zombie shooter using simple graphics (usually squares/rectangles) and that's what I'm currently trying to do in Unity.

I've got to the point where I have:

  • A player that shoots (and is controlled via WASD/arrow keys and mouse)
  • Zombies that spawn and go towards the player
  • Zombies that can be killed (and once all zombies are dead, another wave spawns)

But, currently, it seems that the way I spawn them spawns them way too far away from the player. I use an orthographic camera.

Code:

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

public class ZombieSpawner : MonoBehaviour {
    private int waveNumber = 0;
    public int enemiesAmount = 0;
    public GameObject zombie;
    public Camera cam;
    // Use this for initialization
    void Start () {
        cam = Camera.main;
        enemiesAmount = 0;
    }

// Update is called once per frame
void Update () {
        float height = 2f * cam.orthographicSize;
        float width = height * cam.aspect;
        if (enemiesAmount==0) {
            waveNumber++;
            for (int i = 0; i < waveNumber; i++) {
                Instantiate(zombie, new Vector3(cam.transform.position.x + Random.Range(-width, width),3,cam.transform.position.z+height+Random.Range(10,30)),Quaternion.identity);
                enemiesAmount++;
            }
        }
    }
}

If You want them to spawn zombies just outside camera view don't multiply orthographic size.

float height = cam.orthographicSize; // now zombies spawn od camera view border
float height = cam.orthographicSize + 1 // now they spawn just outside

It'a a small change, but You could also set width as:

float width = cam.orthographicSize * cam.aspect + 1;

Try to spawn another wave when there is one zombie left and see how game pacing has changed ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM