Skip to content

Simple Collision Detection

BearThorne edited this page Oct 16, 2017 · 10 revisions

This tutorial deals with "grid movement"

grid-movement

as opposed to "free movement"
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
Clone this wiki locally