Nested loops for two arrays of objects

Hi there, I am having problems making a ball-line collision method work for an array of balls and a seperate array of lines.

it works for the first element of the movers array if i call the function like so:

for (var t = 0; t < superLines.length; t++ { superLines[t].collision(movers[0].position.x, movers[0].position.y, movers[0].mass*16); }

however, when I have a nested loop, like the following:

for (var t = 0; t < superLines.length; t++ { for (var q = 0; q < movers.length; q++ { superLines[t].collision(movers[q].position.x, movers[q].position.y, movers[q].mass*16); }

the method doesn't even work for the first element in the movers array!

I haven't used a var called q anywhere else in the code :S anyway, I've been stuck for a couple of days on this and googling hasn't helped, although its likely i'm searching the wrong terms.

I'm really confused about the whole thing as I thought that was how you would call such a function and would greatly appreciate any clarity anyone can offer!

I can include the whole code if necessary, but I didn't want to pollute the page as it's about 600 lines long.

Thanks a lot for reading, Leon

Answers

  • edited March 2015
    • Aside from the missing close parens in your for ( ;; ) loops I can't pinpoint any further bugs.
    • Perhaps a less verbose enhanced for ( : ) approach can make things clearer for bug hunt.
    • Don't forget to replace both SuperLine & Mover w/ your actual class names!

    for (SuperLine sl : superLines)  for (Mover mv : movers)
      sl.collision(mv.position.x, mv.position.y, mv.mass*16);
    
  • show your entire code please

  • edited March 2015

    you can change the method

    collision

    and make it so that you can pass the object

    movers[q] to it

    the collision method can then access position.x and position.y etc.

    ;-)

Sign In or Register to comment.