Dear XNA Community,
While designing a trackbar component for an XNA game of mine I was having some issues. I've included the source of the TrackBar/slider at the bottom of this post. Basically, the issue I am having is increasing or decreasing the value of the trackbar depending on where you click on it. Assistance is very much appreciated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace CoreEngine
{
public class TrackBar : Component
{
//Slider values.
private int iMin = 0;
private int iMax = 0;
private int iValue = 0;
SpriteFont Font;
public Vector2 Pos = new Vector2(0, 0);
float ArrowPos;
//Images and textures for the trackbar.
Texture2D Slider;
Texture2D Arrow;
Texture2D CollRect;
//Rectangles used for collision.
Rectangle mouseRectangle;
Rectangle sliderRectangle;
public int Max
{
get
{
return iMax;
}
set
{
iMax = value;
}
}
public int Min
{
get
{
return iMin;
}
set
{
iMin = value;
}
}
public int Value
{
get { return iValue; }
set
{
iValue = value;
if (Value > Max)
iValue = Max;
if (Value < Min)
iValue = Min;
}
}
public TrackBar(int min, int max, int value, Vector2 pos)
{
Min = min;
Max = max;
Value = value;
Pos = pos;
//Load all our graphics.
Slider = Engine.Content.Load<Texture2D>("Content\\Graphics\\UI\\Slider");
Font = Engine.Content.Load<SpriteFont>("Content/Graphics/Fonts/DropMenuText");
Arrow = Engine.Content.Load<Texture2D>("Content\\Graphics\\UI\\Arrow");
CollRect = Engine.Content.Load<Texture2D>("Content\\CollRect");
ArrowPos = Pos.X;
}
public override void Draw()
{
Engine.SpriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Immediate, SaveStateMode.None, Engine.SpriteScale);
Engine.SpriteBatch.Draw(Slider, new Rectangle((int)Pos.X, (int)Pos.Y, Max + 10, Slider.Height), Color.White);
Engine.SpriteBatch.DrawString(Font, Convert.ToString(Value), new Vector2(Pos.X + Max + 20, Pos.Y - 5), Color.White, 0, Vector2.Zero, 0.7f, SpriteEffects.None, 1);
Engine.SpriteBatch.Draw(Arrow, new Rectangle((int)Pos.X + Value, (int)Pos.Y, Arrow.Width, Arrow.Height), Color.Black);
Engine.SpriteBatch.End();
}
public override void Update()
{
mouseRectangle = new Rectangle(Engine.Services.GetService<MouseDevice>().State.X, Engine.Services.GetService<MouseDevice>().State.Y, 3, 3);
sliderRectangle = Conversions.ScaleRectangle(new Rectangle((int)Pos.X, (int)Pos.Y, Max, Slider.Height));
if (mouseRectangle.Intersects(sliderRectangle))
{
if (Engine.ScreenW < 1920)
Value = Value = (int)(mouseRectangle.X - Conversions.ScaleVector(Pos).X);
else
Value = (int)(mouseRectangle.X - Pos.X);
}
}
}
}