If you want to make something like color switch and you want to detect the collision with the circle.
Your circle is described by the class:
public class Circle {
public Vector2 pos = new Vector2(); // Circle center position
public float angle = 0f; // Rotation angle, between 0 and 2*pi
public float innerRadius = 100f; // Inner radius
public float thickness = 10f; // Thickness
// The list of colors in the circle in anticlockwise order.
// Each color takes the same portion of the circle.
public Color[] colors = new Color[]{Color.RED, Color.YELLOW, Color.GREEN, Color.BLUE};
// a constructor here probably, setters, getters...
}
And your ball by the class:
public class Ball {
public Vector2 pos = new Vector2(); // Ball center position
public float radius = 10f; // The ball radius
public Color color = Color.WHITE;
// probably more attributes like vertical speed
// a constructor here probably, setters, getters...
}
On each frame, you update the ball position, circle rotation and then check for collision.
If you want to check if the ball collides with a circle, you have two possibilities:
The ball is completely inside or completely outside the circle. That means the ball can't be colliding with the circle.
Otherwise the ball touches the circle outline. The angle of the ball in the circle must be found to check if the color is right to decide of the collision.
It could look like this:
public boolean isBallCollidingWithCircle(Ball ball, Circle circle) {
// Compute the distance between the circle and ball centers
double dx = (double) (ball.pos.x - circle.pos.x);
double dy = (double) (ball.pos.y - circle.pos.y);
double distance = Math.hypot(dx, dy);
if (distance < circle.innerRadius - ball.radius ||
distance > circle.innerRadius + circle.thickness + ball.radius) {
// No collision possible.
return false;
}
float angle = Math.atan2(dy, dx);
int colorsCount = circle.colors.length
// Not entirely sure about this line, basically find the circle color from the angle.
Color collisionColor = circle.colors[((angle + circle.rotation) / (2 * Math.PI) * colorsCount + colorsCount) % colorsCount];
if (collisionColor.equals(ball.color)) {
// Same color, no collision.
return false;
}
// Not the same color, collision.
return true;
}
Make sure all the coordinates are in a Y-up system since atan2
needs that. I included x
coordinates but I'm not sure if that's necessary for Color Switch.
I cut some corners obviously, for example if the ball inside the circle outline, no collision will be detected until the ball center touches the wrong color (and not the ball outline). If you really plan on making a game similar to Color Switch, I encourage you to use box2d for easier collision detection. (circle-circle collision is simple, but circle-polygon is something else...)