Skip to content

Instantly share code, notes, and snippets.

@Achie72
Created March 16, 2025 09:53
Show Gist options
  • Save Achie72/c4770b9e9beda1e312103ae7792b5c8b to your computer and use it in GitHub Desktop.
Save Achie72/c4770b9e9beda1e312103ae7792b5c8b to your computer and use it in GitHub Desktop.
How to spawn stuff in PICO-8 with a function
-- create a table to hold your objects
coins ={}
--now you can add things into here by hand, but you can also make a functionnsonyou can call that point
function add_coin(xpos, ypos)
-- now lets make a temporary local table to hold the coins atrributes, you want position mainly
local coin = {
x = xpos,
y = ypos
}
-- you now have a coin object but no way to track it as it will die once you exit the function. Lets add it tonthe global table. add(tablename, value)
add(coins, coin)
end
-- now you can iterate over your coins inside the coin table with any for cycle. If you want to deletenobjects you generally want to go backwards. In update
function update_coins()
for i=#coins,1,-1 do
-- this will make i go from the size of the coins table to 1
--you can grab elements from the table in an easy way
local coin = coins[i]
-- this will put each coin inside coins into this coin variable 1 by 1, you can now move them if you want
coin.y +=1
-- now for example delete them if they are offscreen
if coin.y > 128 then
del(coins, coin)
end
end
--[[
yoiu can do the same with a for all in() cycle
for coin in all(coins) do
coin.y +=1
-- now for example delete them if they are offscreen
if coin.y > 128 then
del(coins, coin)
end
end
]]--
end
-- now in draw you can do
function draw_coins()
for i=#coins,1,-1 do
local coin = coins[i]
-- you now known where it is on the screen
print("◆", coin.x, coin.y,9)
end
end
-- with all this setup you csn just add a coin whenever you want with, where the two numbers all the positions
function _update()
if btnp(4) then
add_coin(rnd(128), rnd(128))
end
update_coins()
end
function _draw()
cls()
draw_coins()
end
@Achie72
Copy link
Author

Achie72 commented Mar 16, 2025

Do you want add a bullet, that goes forward? Modify the update so it is:

coin.x += 2

and remove the coin.y modification now it is moving from side to side just like a bullet!

@Achie72
Copy link
Author

Achie72 commented Mar 16, 2025

@Achie72
Copy link
Author

Achie72 commented Mar 16, 2025

If you would like to read more like this, feel free to checkout my Ko-fi articles, with many devlogs and code rundowns like this!
https://github.com/Achie72/kofi-articles

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment