To skip this chapter use the following link
So lets add some challenge by adding some enemies that respawn outside the view and slowly going towards the player.
Draw a sprite for the enemy... how about a ghost?
As with particles we need a table for all the enemies, and do the same draw and update tango as with everything else:
FUNCTION _INIT()
-- SNIP SNIP
ENEMIES={}
END
FUNCTION _DRAW()
-- SNIP SNIP
FOR E IN ALL(ENEMIES) DO
E:DRAW()
END
END
FUNCTION _UPDATE()
-- SNIP SNIP
FOR E IN ALL(ENEMIES) DO
E:UPDATE()
END
END
Drawing the ghost is as simple as drawing the sprite:
FUNCTION DRAW_ENEMY(E)
SPR(3,E.X,E.Y)
END
We want the ghost to chase the player, so first figure out what the angle is between both and then change the position of the ghost towards the player. PICO-8 API has ATAN2
function that lets you get the angle with a given x,y vector.
FUNCTION UPDATE_ENEMY(E)
LOCAL DX=PLAYER.X-E.X
LOCAL DY=PLAYER.Y-E.Y
LOCAL A=ATAN2(DX,DY)-0.25
E.X+=SIN(A)
E.Y-=COS(A) -- REMEMBER THE SCREEN IS FLIPPED
END
Lets write a function to add a ghost and to add one initial ghost in _INIT
. Spawn the ghost 68 pixels away from the center.
FUNCTION _INIT()
-- SNIP SNIP
ADD_ENEMY()
END
FUNCTION ADD_ENEMY()
LOCAL A=RND(1)
ADD(ENEMIES, {
X=64-(SIN(A)*68),
Y=64-(COS(A)*68),
DRAW=DRAW_ENEMY,
UPDATE=UPDATE_ENEMY
})
END
The enemy should move around like this when running the program:
Okay, lets spawn more ghosts in regular intervals to do this, we need to keep track of when to spawn the next ghost. How about every 2 seconds? We can get the game time with the T
function. So lets have a state variable that tells when next enemy will spawn. We can initiate this in ADD_ENEMY
since it is already called in the _INIT
and will set a new time for next enemy to spawn:
FUNCTION ADD_ENEMY()
NEXT_ENEMY=T()+2 -- T returns game time in seconds
-- SNIP SNIP
END
And lets do the spawning in the _UPDATE
function when the time has passed:
FUNCTION _UPDATE()
-- SNIP SNIP
IF T() > NEXT_ENEMY THEN
ADD_ENEMY()
END
END
The game should now spawn ghosts every 2nd second.
ATAN(X,Y)
gives you the angle from 0,0 to X,Y (aka. a vector).- The
T
function gives you the current game time in seconds