Game Development Reference
In-Depth Information
this .Add(back);
front = new SpriteGameObject(sliderfront, 1);
front.Position = new Vector2(leftmargin, 8);
this .Add(front);
dragging = false ;
}
As you can see, we also set a boolean variable dragging to false . We will need this
variable to keep track of when the player is dragging the slider so that we update
the slider position when needed, even when the mouse pointer is not within the
boundaries of the back sprite.
The next step is adding a property Value that allows us to retrieve and set the
value of the slider. We want a value of 0 to indicate that the slider is fully moved
to the left, and a value of 1 to indicate the fully right position of the slider. We can
calculate the current value by looking at the position of the front sprite, and seeing
how much it is moved to the right. Therefore, the following line of code calculates
the slider value from the slider position:
back.Position.X leftmargin) /
return (front.Position.X
leftmargin rightmargin front.Width);
(back.Width
In the upper part of the fraction, we calculate how far to the right the front sprite has
been moved. We calculate this locally to the back position plus the left margin. We
then divide this by the total length that the slider can move. This return -instruction
forms the get part of the Value property. For the set part of the property, we need to
convert a value between zero and one to the front slider x position. This amounts to
rewriting the above formula such that the front x position is the unknown, which is
then calculated as follows:
float newxpos = value
(back.Width
leftmargin
rightmargin
front.Width)
+ back.Position.X + leftmargin;
All that remains to be done now is to create the new front position vector with the
correct x position:
front.Position = new Vector2(newxpos, front.Position.Y);
So, now that we have a way to set and get the slider value, we still need to deal with
the mouse input to drag the slider to a new position. This is done by overriding the
HandleInput method. If the left mouse button is down, we have to check if we are
dragging the slider. This is the case if the mouse position is within the bounding
box of the back sprite, or if we were already dragging . This latter condition allows
us to continue dragging the slider when the mouse moves outside of the back sprite
bounding box. If so, we calculate the new x position of the slider bar. Ideally we
Search WWH ::




Custom Search