To skip this chapter use the following link
We want our player token pick up all the cherry tokens it reaches. For this we need to implement a collision check. Unfortunately PICO-8 API doesn't provide one, so you'll need to make one yourself.
The easiest way to do a collision check is to check if both the player token and any cherry is close enough. We can check the distance between points, such as the center of player and cherry and see if it is less than 4 pixels or so.
A distance function, if you don't remember math, is given from pythagorean function. You may create a function that takes two tables (that presumably have X and Y) and calculate the distance. We need to define some variables, and to not pollute the global scope you can use LOCAL
to define variables to be bound by the function scope it is in:
FUNCTION DIST(A,B)
LOCAL DX,DY=A.X-B.X,A.Y-B.Y
RETURN SQRT(DX*DX+DY*DY)
END
Now lets use that in our _UPDATE
function and check the distances with with our DIST
function between all cherries and the player. IF
they are close enough THEN
remove the cherry with PICO-8's DEL
function.
FUNCTION _UPDATE()
PLAYER:UPDATE()
FOR CHERRY IN ALL(CHERRIES) DO
IF DIST(PLAYER, CHERRY)<4 THEN
DEL(CHERRIES, CHERRY)
END
END
END
Do note that as with FOR
loops, IF
-statements in LUA doesn't need parenthesis for it's arguments.
Running CTRL+R you'll be able to pick up the cherries in the stage now.
IF-THEN-END
statements for decisions, like in other languages No need for parenthesis to enclose the expressionDEL
removes/deletes the given object from the given table