using System; using System.Collections.Generic; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; // Our own library using XnaAssignments; namespace SimpleXNA { class Ball { #region Instance Variables private const float RADIUS = 0.25f; // Radius to make it look right private const float SPEED = 0.1f; // To make it look right private Vector2 m_Position; // Position of the ball private Vector2 m_Velocity; // Velocity of the ball private int m_BounceCount; // Number of bounces private bool m_Expired; // Still valid (in bound) #endregion #region Constructor: notice the randomness in initial velocity! public Ball(Vector2 p) { m_Expired = false; // Create some simple randomness in the velocity m_Velocity.X = Game1.RandomNumber(); m_Velocity.Y = Math.Abs(m_Velocity.X) * 5.0f; // go more in the y-direction m_Velocity.Normalize(); m_Velocity *= (SPEED + (0.3f * Game1.RandomNumber() * SPEED)); m_Position = p; m_BounceCount = 0; } #endregion #region Access and update number of bounces public void Bounce() { m_BounceCount++; } public int NumBounce { get { return m_BounceCount; } } #endregion #region Access position, velocity, radius, and expiration public Vector2 Velocity { set { m_Velocity = value; } get { return m_Velocity; } } public Vector2 Position { set { m_Position = value; } get { return m_Position; } } public float Radius { get { return RADIUS; } } public bool Expired { get { return m_Expired; } } #endregion #region Bounds: min and max bounds of the ball public Vector2 MinBound { get { Vector2 b = new Vector2(m_Position.X - RADIUS, m_Position.Y - RADIUS); return b; } } public Vector2 MaxBound { get { Vector2 b = new Vector2(m_Position.X + RADIUS, m_Position.Y + RADIUS); return b; } } #endregion #region Draw and Update: move the ball and check for bounds (notice expire!) public void Update() { m_Position += m_Velocity; Vector2 min = MinBound; Vector2 max = MaxBound; if (max.X > XnaAssignmentBase.WorldMax.X) { m_Position.X = XnaAssignmentBase.WorldMax.X - RADIUS; m_Velocity.X = -m_Velocity.X; } else if (min.X < XnaAssignmentBase.WorldMin.X) { m_Position.X = XnaAssignmentBase.WorldMin.X + RADIUS; m_Velocity.X = -m_Velocity.X; } if (max.Y > XnaAssignmentBase.WorldMax.Y) { m_Position.Y = XnaAssignmentBase.WorldMax.Y - RADIUS; m_Velocity.Y = -m_Velocity.Y; } else if (min.Y < XnaAssignmentBase.WorldMin.Y) { m_Expired = true; } } public void Draw() { XnaAssignmentBase.DrawCircle(m_Position, RADIUS, 0.0f, Color.Aquamarine, Color.Pink, null); } #endregion } }