Difference between revisions of "DistanceBasedCollision"

(added a simpler function.)
(Added missing property for the category page.)
Line 1: Line 1:
 
Another way of detecting collisions. This type works perfectly with circles.
 
Another way of detecting collisions. This type works perfectly with circles.
It checks if the distance of one object to the other is less than the sum of their radii(plural of radius.)
+
It checks if the distance of one object to the other is less than the sum of their radii (plural of radius.)
  
Variable Definitions : ax, ay = circleA's coordinates; bx, by = circleB's coordinates; ar, br = circleA's and circleB's radii, respectively  
+
Variable Definitions : ax, ay = circleA's center coordinates; bx, by = circleB's center coordinates; ar, br = circleA's and circleB's radii, respectively.
  
 
<source lang="lua">
 
<source lang="lua">
Line 24: Line 24:
 
Although I do keep the sqrt function to know that I am dealing with distances.
 
Although I do keep the sqrt function to know that I am dealing with distances.
  
== Contributors ==
+
Do note that while the second may seem faster since it avoids a costly square root, that's still one function, instead of the second version's three squarings. That said, Löve uses LuaJIT, so if one really needs to optimize, check which is faster.
* [[User:Substitute541|Substitute541]]
 
  
 
[[Category:Snippets]]
 
[[Category:Snippets]]
 
{{#set:Author=User:Substitute541}}
 
{{#set:Author=User:Substitute541}}
 +
{{#set:LOVE Version=any}}
 
{{#set:Description=Another way of detecting collisions. This type works perfectly with circles.}}
 
{{#set:Description=Another way of detecting collisions. This type works perfectly with circles.}}
 
== Other Languages ==
 
== Other Languages ==
 
{{i18n|DistanceBasedCollision}}
 
{{i18n|DistanceBasedCollision}}

Revision as of 17:35, 11 November 2016

Another way of detecting collisions. This type works perfectly with circles. It checks if the distance of one object to the other is less than the sum of their radii (plural of radius.)

Variable Definitions : ax, ay = circleA's center coordinates; bx, by = circleB's center coordinates; ar, br = circleA's and circleB's radii, respectively.

function checkCircularCollision(ax, ay, bx, by, ar, br)
	local dx = bx - ax
	local dy = by - ay
	local dist = math.sqrt(dx * dx + dy * dy)
	return dist < ar + br
end

Don't want an extra square root function? Try this other function

function checkCircularCollision(ax, ay, bx, by, ar, br)
	local dx = bx - ax
	local dy = by - ay
	return dx^2 + dy^2 < (ar + br)^2
end

Although I do keep the sqrt function to know that I am dealing with distances.

Do note that while the second may seem faster since it avoids a costly square root, that's still one function, instead of the second version's three squarings. That said, Löve uses LuaJIT, so if one really needs to optimize, check which is faster.


Other Languages