Log In  

Hello,
I'm doing some Lua pseudo-OOP stuff, and I want to check if tables within a shared table are colliding.
I have a simple AABB check-collision function that takes the x, y, width, and height of two objects and returns true or false if they're intersecting or not.

I'm assuming I should loop through the main table like so

FOR K,V IN PAIRS(DUDES) DO
 IF CHECK_COLLISION(V.X,V.Y,V.W,V.H ... THEN
  DO_STUFF()
 END
END

I'm not sure how to reference a value of the next table from the same table. I've tried

 IF CHECK_COLLISION(V.X,V.Y,V.W,V.H,DUDES[K+1].X,DUDES[K+1].Y,DUDES[K+1].W,DUDES[K+1].H

and a few similar methods, but none of them seem to work. I think I'm headed in the wrong direction, but I can't figure it out. Do I need to do some nested looping to index each table DUDE within DUDES, or use a different method from pairs?

P#19419 2016-03-26 18:37 ( Edited 2016-03-27 00:17)

I'm not sure I understand what the structure of your DUDES table is and what total set of collisions you want to check for, but here's how I'd do it for one set of assumptions:

  1. DUDES is a table of DUDE objects, each DUDE object itself a collection of parameters including .x, .y, .w, and .h, something like:
ADUDE = {x=20, y=30, w=8, h=8}
ALSODUDE = {x=25, y=31, w=8, h=8}
...
DUDES = {ADUDE, ALSODUDE,...}
  1. You want to collide every pair of DUDE objects in the DUDES list, not just all of those DUDE objects against some single other collideable object.

For that I'd do a nested pair of for loops, like this:

FOR N=1,COUNT(DUDES)-1 DO
  FOR M=N,COUNT(DUDES) DO
    LOCAL D1=DUDES[N]
    LOCAL D2=DUDES[M]
    LOCAL COL = CHECK_COLLISION(
      D1.X,D1.Y,D1.W,D1.H,
      D2.X,D2.Y,D2.W,D2.H)
    IF(COL) THEN 
      -- GET YOUR COLLIDE ON
    END
  END
END

That'll get you a comparison between each pair of DUDE objects in DUDES exactly once. You could skip those LOCAL declarations obviously, but makes for more readable code to break it down like that vs. long-ass lines.

P#19421 2016-03-26 19:08 ( Edited 2016-03-26 23:08)

Hey, thanks so much!
You understood what I was asking exactly, and your solution let me to the answer I needed. ^.^

P#19423 2016-03-26 20:09 ( Edited 2016-03-27 00:09)

Yay! Glad to help, keep on codin'.

P#19424 2016-03-26 20:17 ( Edited 2016-03-27 00:17)

[Please log in to post a comment]

Follow Lexaloffle:        
Generated 2020-05-29 04:07 | 0.010s | 4194k | Q:18