Collision check with double For - Each

BlitzPlus Forums/BlitzPlus Programming/Collision check with double For - Each

havok2(Posted 2013) [#1]
Hello,
I try to made a new Version from comet busters 1994, because it do not work on 64-bit-machine. But I have a little Problem in understannding the For-Each

in my code every "circle" had to check if it collide with a other one. But x2,y2 and r2 gets every loop the same value like x1,y2 and r1?

For c.circle = Each circle	
	;define values for Circle1
	x1 = c\pos_x
	y1 = c\pos_y
	r1 = c\radius
	For c2.circle = Each circle
		;define values for Circle2
		x2 = c2\pos_x
		y2 = c2\pos_y
		r2 = c2\radius
		
		;calculate distance and sum of diameter
		r = r1+r2
		dist_x = x2-x1
		dist_y = y2-y1
		dist = Sqr((dist_x*dist_x)+(dist_y*dist_y))
						
		;on collision
		If dist <= r
			;Explosion(c2\pos_x, c2\pos_y, 4, 10, 0, 360, 4, 0, 
		EndIf				
	Next
Next


I hope someone can help me - thx =)


Yasha(Posted 2013) [#2]
Well one thing you need is to make sure that you don't end up comparing a circle to itself - since the inner loop also examines all circles, it will at some stage reach the same circle being described by the outer loop. This has the unfortunate effect that every circle will collide with itself, and explode immediately.

To correct this, just place everything within the c2 loop inside an If block with 'c <> c2' as the condition check. That should help.


Floyd(Posted 2013) [#3]
Here's an example of working with two list items, but checking each pair just once.
In the example t1 always precedes t2 in the list.

Type thing
	Field n
End Type

Local t1.thing, t2.thing

For k = 1 To 4
	t1 = New thing
	t1\n = k
Next

t1 = First thing
While t1 <> Null
	t2 = After t1
	While t2 <> Null
		Print "Check things " + t1\n + " and " + t2\n
		t2 = After t2
	Wend	
	t1 = After t1
Wend

WaitKey



havok2(Posted 2013) [#4]
That is amazing. I'm coding some stuff as hobby. Since school on the Casio GTX. I coded something like this very often. But never efficient like this. I needed a sheet of paper with lots of arrows on it to understand how it works. Thank you very much!

Is the greatest thing to learn something by understanding it.
Best Regards from Germany