Thursday, June 23, 2016

c# - How to solve the overlap of two circles that collide


I have two circles, one of the circles is static the other is moving around. I have a method that checks whether the two circles collide. How to make the two circles don't overlap when colliding?


public void UpdateGame()
{
//keyboard input and moving the circle here

if(CollisionDetection(dynamicCircle,staticCircle)
{
ResolveOverlap(dynamicCircle,staticCircle);
}

}

public class CircleBody
{
public Vector2 position {get;set;} // top left corner
public float CenterX;
public float CenterY;
public int Width { get; set; }
public int Height { get; set; }
}


public bool CollisionDetection(CircleBody body1, CircleBody body2)
{
float radius = body1.Radius + body2.Radius;
float distanceBetweenTwoCircles = ((body1.CenterX - body2.CenterX) *
(body1.CenterX - body2.CenterX)) +
((body1.CenterY - body2.CenterY) *
(body1.CenterY - body2.CenterY));

if(radius > Math.Sqrt(distanceBetweenTwoCircles))

{
return true;
}
return false;
}

public void ResolveOverlap(CircleBody body1, CircleBody body2)
{
//answer to my question
}


If it wasnt clear by now here is my code for solving that with two rectangles I want the same thing to happen to the circles.


public void ResolveOverlap(RectangleBody body1, RectangleBody body2)
{
double widthY = (0.5 * (body1.Width + body2.Width)) * (body1.CenterY - body2.CenterY);
double heightX = (0.5 * (body1.Height + body2.Height)) * (body1.CenterX - body2.CenterX);

if (widthY > heightX)
{
if (widthY > -heightX)

{
//collision - top
body1.Position.Y = body2.Position.Y + body2.Height;
}
else
{
//collision - right
body1.Position.X = body2.Position.X - body1.Width;
}
}

else
{
if (widthY > -heightX)
{
//collision - left
body1.Position.X = body2.Position.X + body2.Width;
}
else
{
// collision - bottom

body1.Position.Y = body2.Position.Y - body2.Height;
}
}
}


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...