-
-
Notifications
You must be signed in to change notification settings - Fork 502
Simple Collision Detection
This tutorial deals with "grid movement"
as opposed to "free movement"
It's a little simpler to handle, and I feel that grid movement has a more retro feel to it.
If your interested in free movement detection, then check out the "Simple Platformer Tutorial" by Tremelar.
https://github.com/nesbox/TIC-80/wiki/Simple-Platformer-tutorial
It deals with free movement collision pretty well. That being said, let's go.
the basic code we will be using is:
-- title: simple collision detection
-- author: Bear Thorne
-- desc: Detecting Collision for Grid Movement
-- script: lua
--VARIABLES
--sprite vars
FLOOR=1 --the floor sprite will be stored in the 1 slot
WALL=17 --the wall sprite will be stored in the 17 slot
DUDE=33 --the player sprite will be stored in the 33 slot
--game constants
SCREEN_X=29
SCREEN_Y=16
--player object
p={
x=SCREEN_X//2, --center of screen x
y=SCREEN_Y//2} --center of screen y
--FUNCTIONS
--player movement
--we'll use the btnp() function to detect a single button
--press, and then repeats at a given interval
function move()
--player presses "up"
if btnp(0) then
p.y=p.y-1
end
--player presses "down"
if btnp(1) then
p.y=p.y+1
end
--player presses "left"
if btnp(2) then
p.x=p.x-1
end
--player presses "right"
if btnp(3) then
p.x=p.x+1
end
end
--draw screen graphics
function draw()
cls()
map(0,0,SCREEN_X+1,SCREEN_Y+1)
--multiplying the player coors by 8 (the size of the map cells)
--gives us grid movement
spr(DUDE,p.x*8,p.y*8,0)
end
function TIC()
move()
draw()
end
This code can move the player around the screen, but it doesn't deal with collision yet. The player can walk through walls like a ghost at the moment. we'll deal movement collision first.
the first step is to write a function for checking the map cell ahead of the player, and determining if it's clear or not. And to check that we need to include some direction constants like so...
DIRECTIONS
--Direction constants
U={x= 0,y=-1}, --up
D={x= 0,y=+1}, --down
L={x=-1,y= 0}, --left
R={x=+1,y= 0}} --right
TIC-80 tiny computer https://tic80.com | Twitter | Telegram | Terms
Built-in Editors
Console
Platform
RAM & VRAM | Display | Palette | Bits per Pixel (BPP) |
.tic
Format | Supported Languages
Other
Tutorials | Code Snippets | Libraries | External Tools | FFT
API
- BDR (0.90)
- BOOT (1.0)
- MENU
- OVR (deprecated)
- SCN (deprecated)
- TIC
- btn & btnp
- circ & circb
- clip
- cls
- elli & ellib (0.90)
- exit
- fget & fset (0.80)
- font
- key & keyp
- line
- map
- memcpy & memset
- mget & mset
- mouse
- music
- peek, peek4
- peek1, peek2 (1.0)
- pix
- pmem
- poke, poke4
- poke1, poke2 (1.0)
- rect & rectb
- reset
- sfx
- spr
- sync
- ttri (1.0)
- time
- trace
- tri & trib (0.90)
- tstamp (0.80)
- vbank (1.0)