Search Unity

Spawn targets at a random position but not blocked by objects

Discussion in 'Scripting' started by unity3dat, Sep 24, 2017.

  1. unity3dat

    unity3dat

    Joined:
    Aug 9, 2017
    Posts:
    88
    I'm using this script in my FPS to spawn enemies at a random position (every 5 seconds), but always within the camera view:

    Code (CSharp):
    1. Vector3 screenPosition = Camera.main.ScreenToWorldPoint(new Vector3(Random.Range(0,Screen.width), Random.Range(0,Screen.height), Camera.main.farClipPlane/2));
    Of course, the floor where my character stands on, blocks the view a bit. With the code above, the enemy can spawn beneath the floor because technically it's within the camera view, but the floor blocks it.

    Also, there are houses in my game environment. With the code above, enemies can spawn behind a house so the character can't see them.

    I'm looking for a way to resolve both issues. They can both be resolved if I could add this to my script: "an enemy must always spawn in the camera view AND cannot be blocked by other objects".

    Any idea how I could change my script to address this issue?

    I was thinking of a way to detect whether or not an object is blocked, and if it is, make it respawn. But I'm afraid this will affect the time the spawning occurs (which should always be 5 seconds, even if it has to recalculate a couple of times because the enemy was blocked).
     
  2. Rob21894

    Rob21894

    Joined:
    Nov 21, 2013
    Posts:
    309
    Check out OverlapSphere and OverlapBox you can cast one of these before the enemy spawns to check there is no walls nearby and if there is keep checking until theres a free space available

    https://docs.unity3d.com/ScriptReference/Physics.OverlapBox.html

    You could also approach this in another ways with a bit of research on spawning
     
  3. lordconstant

    lordconstant

    Joined:
    Jul 4, 2013
    Posts:
    389
    You can acheive what you want with two raycasts (as long as you dont mind your targets being infront of the houses).

    First do a raycast down from the found spawn point to find the floor.

    Update your spawn to the floor.

    Now do another raycast to the updated point from the player.

    If it hits anything bring it to that point instead (use the spawn objects radius to avoid clipping into the wall).

    Now you can spawn knowing the player can see the target.