Fun Infused Games  |   Smooth Operator RSS 

  Home   |    Archive   |    Subscribe   |    Search   |    About
Circle class for C# / XNA
Date 3/29/2011    Tags XNA    (0)

Ever find yourself in need of a circle in C# / XNA and can't do it? Now you can AND you can test if your circle collides with a rectangle too. I'm pretty sure I got the circle class itself from somewhere else (if it's you, let me know and I will credit you) but I wrote the Intersects() method all by myself... at least I'm pretty sure I did.
/// <summary> 
/// Represents a 2D circle. 
/// </summary> 
public struct Circle
{
    private Vector2 v;
    private Vector2 direction;
    private float distanceSquared;

    /// <summary> 
    /// Center position of the circle. 
    /// </summary> 
    public Vector2 Center;

    /// <summary> 
    /// Radius of the circle. 
    /// </summary> 
    public float Radius;

    /// <summary> 
    /// Constructs a new circle. 
    /// </summary> 
    public Circle(Vector2 position, float radius)
    {
        this.distanceSquared = 0f;
        this.direction = Vector2.Zero;
        this.v = Vector2.Zero;
        this.Center = position;
        this.Radius = radius;
    }

    /// <summary> 
    /// Determines if a circle intersects a rectangle. 
    /// </summary> 
    /// <returns>True if the circle and rectangle overlap. False otherwise.</returns> 
    public bool Intersects(Rectangle rectangle)
    {
        this.v = new Vector2(MathHelper.Clamp(Center.X, rectangle.Left, rectangle.Right),
                                MathHelper.Clamp(Center.Y, rectangle.Top, rectangle.Bottom));

        this.direction = Center - v;
        this.distanceSquared = direction.LengthSquared();

        return ((distanceSquared > 0) && (distanceSquared < Radius * Radius));
    }
}



This article has been view 2926 times.


Comments

No comments for this article.


Add Comments

Name *
Website
  Name the animal in the picture below:

*  
Comment *
Insert Cancel


Tags
ASP.net (18)  Fin (1)  Video Games (7)  Game Dev (11)  Abduction Action (1)  WP7 (8)  Visual Studio (1)  Hypership (28)  Advise (14)  C# (14)  FIN (20)  World of Chalk (2)  Absurd (2)  Abduction Action! (27)  Nasty (34)  PC (1)  Cool (2)  Sports (11)  Rant (50)  VolChaos (1)  Development (13)  Design (2)  Volchaos (11)  XNA (40)  Nastier (4)  Xbox (1)  iOS (3)  SQL (1)  XBLIG (32)  Trivia or Die (3)  Web (19)  Trivia Or Die (1)  Abdction Action! (1)