Cicle Detection

Blitz3D Forums/Blitz3D Programming/Cicle Detection

Tibit(Posted 2004) [#1]
How shoudl I do if I want to check if something is within a circle? In 2D.

Example, if someone is caught in an exlopision then I want that area to be circular not square. I know one solution is to calculate the distance to the center of the explosion and then check each object if it is closer than that, but this seems to be an inefficient way, or?


Rob Farley(Posted 2004) [#2]
Just knocked this together...

The function returns true or false depending on if the circles are touching or not. Send in the x y and radius of each circle... The code under the function is just for demo purposes so kill it off once you've got the idea!

Function incircle(x1,y1,r1,x2,y2,r2)
	x=(x1-x2)
	y=(y1-y2)
	If Sqr((x*x)+(y*y))<= (r1+r2) Then Return True Else Return False
End Function





; example code... just to show off the function

Graphics 640,480

Repeat

	x1=Rand(0,640)
	y1=Rand(0,480)
	r1=Rand(10,100)
	
	x2=Rand(0,640)
	y2=Rand(0,480)
	r2=Rand(10,100)
	
	Oval x1-r1,y1-r1,r1*2,r1*2,False
	Oval x2-r2,y2-r2,r2*2,r2*2,False
	
	Text 0,0,incircle(x1,y1,r1,x2,y2,r2)
	
	WaitKey
	Cls
	
Until KeyHit(1)



semar(Posted 2004) [#3]
Or just simply check for collision between two sprites: one represents the circle of your explosion, the other is your sprite to be ckecked for damage. Since ImagesCollide does not need that you really draw the two images on the screen, you can check for damage while drawing whatever you like.

1) Build up an image, say 100*100, black backround, a red circle in the middle; this is your explosion image img_exp.

2) now simply check for damage:
if imagescollide(img_exp,expx,expy,0,your_sprite,spritex,spritey,spriteframe) then
;damage !
endif

Note that:
img_exp is your explosion image
expx,expy are the 2D coordinates where your real explosion take place
your_sprite is the sprite to be ckecked for damage
your_spritex,your_spritey are the 2D coordinates of your sprite
spriteframe is the frame of your sprite, or 0 if it's only one frame.

Hope it helps,
Sergio.


Tibit(Posted 2004) [#4]
That's smart, It wasn't more complicated than that =)

Isn't sprite to sprite quite slow?
Still it is a good way to do collision against objects that are neither rectangular or circular.

Thanks!


semar(Posted 2004) [#5]
I mean 2D sprites here, and ImagesCollide is really fast !

Sergio.


big10p(Posted 2004) [#6]
Must admit, I was quite surprised at the speed of ImagesCollide. Displaying a couple thousand sprites and it wasn't appreciably slower than RectsOverlap.

Mind you, I think ImagesCollide does a RectsOverlap check before even bothering to check for per-pixel collisions. :)