Answer the question
In order to leave comments, you need to log in
How to calculate the collision of a circle with another object?
Good day. I am making a platformer, and it came to the development of colliders, intersections. A question arose before me. I can calculate whether objects collide with straight lines, but what about a circle, that is, for example, how to understand if the edge of the circle touches the side of the square? Please throw some material about this, poke into the geometry for grade 8: D
Answer the question
In order to leave comments, you need to log in
In general, a lot of things are written about this in books on game development in js. If I'm not confused, then I used a method related to calculating the distance from the center of the circle to the object, and if the distance was <= radius, then a collision occurred.
An example from the book "Build your own 2D Game Engine and Create Great Web Games (Apress, 2015)" (I did not follow it, but it seems to be the same principle)
RigidShape.prototype.collidedRectCirc = function(rect1Shape, circ2Shape) {
var rect1Pos = rect1Shape.getPosition();
var circ2Pos = circ2Shape.getPosition();
if (rect1Shape.containsPos(circ2Pos) || (circ2Shape.containsPos(rect1Pos))) {
return true;
}
var vFrom1to2 = [0, 0];
vec2.subtract(vFrom1to2, circ2Pos, rect1Pos);
var vec = vec2.clone(vFrom1to2);
var alongX = rect1Shape.getWidth() / 2;
var alongY = rect1Shape.getHeight() / 2;
vec[0] = this.clamp(vec[0], -alongX, alongX);
vec[1] = this.clamp(vec[1], -alongY, alongY);
var normal = [0, 0];
vec2.subtract(normal, vFrom1to2, vec);
var distSqr = vec2.squaredLength(normal);
var rSqr = circ2Shape.getRadius() * circ2Shape.getRadius();
return (distSqr < rSqr);
};
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question