This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Lewisk3's profile picture

Help With Collision Detection

Started by Lewisk3, 01 June 2014 - 08:06 AM
Lewisk3 #1
Posted 01 June 2014 - 10:06 AM
i see all these computercraft games and apis with collision detection and are almost impossible to figure out there code due to the maze of function so can someone
just explain to me how collision detection would work in lua?
ardera #2
Posted 01 June 2014 - 10:39 AM
It varies on how your world is set up, and a bit from 2D to 3D.

Example when you have 2D, and the map is a set of strings, where the table indexes are y values.

local map = {
  "OOOO OO  OO",  -- the line is the Y value
  "OOO   O   O",  -- the position in the string the X value
  "O         O",  -- the "O"s are the walls
  "OOO	   OOO",  -- spaces are free space
  "OOOOOOOOOOO"
}


local playerposition = {x = 3, y = 4}  -- the player is standing at x=3, y=4

-- we get the line y=4 of the map
local line = map[playerposition.y]

-- now we get the character at the x=3 position of the line
local char = string.sub(line, playerposition.x, playerposition.x)


-- if the char equals O, the player is in a wall
if char == "O" then
  -- collision!
  print("Player collided!")
else
  -- no collision.
  print("Player didn't collide.")
end
Edited on 01 June 2014 - 08:39 AM
Bomb Bloke #3
Posted 01 June 2014 - 11:43 AM
If that isn't exactly what you're after, then I'd also ask - what sort of shapes are you checking?
Lewisk3 #4
Posted 02 June 2014 - 12:00 AM
If that isn't exactly what you're after, then I'd also ask - what sort of shapes are you checking?
square
Edited on 01 June 2014 - 10:01 PM
Bomb Bloke #5
Posted 02 June 2014 - 02:58 AM
I'll assume by that you're meaning something other than "one pixel".

Say you've got two rectangles, each with four sides. The easiest way to determine whether they're touching is to check against the four circumstances in which you'd know they're not, and if none of them are true, then you've got a collision.

Say Left1 is the left of your first shape, Right1 is the right, Left2 is the left of your second shape, and so on. The first circumstance in which the shapes aren't touching is when Left1 is located to the right of Right2. The second circumstance is when Top1 is below Bottom2… and so on.

The final check hence goes along the lines of:

if not (Left1 > Right2 or Left2 > Right1 or Top1 > Bottom2 or Top2 > Bottom1) then