How do I let sprites spawn randomly in the layout but outside of viewport?

0 favourites
  • 3 posts
From the Asset Store
Who wants to be a Millionaire Clone. An educational coding source
  • I tired searching for a solution, but most of them where several years old and complicated. I hope there is something better now.

    I have a layout that is much bigger then the viewport. The viewport is following the player. Now I want to spawn an enemy every x seconds inside the viewport. I'll do it like this:

    Every X Seconds > create object on layer 0 at (random(64, Layoutwidth-64), random(64, LayouthHeight-64))

    This should for spawning the enemy somewhere in the layout. But I want to avoid spawning an enemy in the viewport. In the best case it would just look awkward, in the worst case the enemy would spawn directly in front of the player.

    I know I could spawn them outside the viewport and then let them move into the layout but there is a barrier around my level which means the player could see that the enemy is just walking over it. Also this would make it harder to keep the enemy inside the layout once it entered it.

    So, what is the easiest way to prevent an enemy from spawning in the viewport? Spawn it randomly and right after it spawns check if its in the viewport and if yes move it randomly again and repeat this until it spawned outside the viewport? Would the multiple spawning happen at the same frame or will the player see the enemy flash for one frame? How do I prevent the enemy from randomly changing it's position when it later legally enters the viewport?

    Create 4 spawn areas around the viewport, north, south, west and east of it. I think of something like

    create object on layer 0 at (random(64, ViewportLeft), (random(64, LayoutHeight-64))

    Make this for alle 4 directions and randomly pick one?

    Or is there even just an option to set that says "don't spawn in view port"?

    Conpletely different solutions?

  • Try Construct 3

    Develop games in your browser. Powerful, performant & highly capable.

    Try Now Construct 3 users don't see these ads
  • You can spawn an enemy, and then move it if it's inside the viewport:

    Enemy on created:
    
     Repeat 100 times
     	if Enemy.X between ViewportLeft(layer) and ViewportRight(layer)
     	and Enemy.Y between ViewportTop(layer) and ViewportBottom(layer)
    		Enemy set position to random.....
    	Else
    		Stop loop
    

    In the worst case scenario if a valid position is not found after 100 attempts, the enemy will appear inside the viewport.

  • Thanks. I'll try that.

Jump to:
Active Users
There are 1 visitors browsing this topic (0 users and 1 guests)