I want to use a trackbar for a game that I'm working on using Winforms in VS2013.
The idea is that the user should choose on how fast a ball goes using a trackbar (use the value from the track bar for another variable in a different class).
Here's the code I currently have:
public static int trackBarValue;
//... Other global variables
public Form1()
{
//... Other code
}
private void trackBar1_Scroll(object sender, EventArgs e)
{
trackBarValue = trackBar1.Value;
}
private void timer1_Tick(object sender, EventArgs e)
{
ball.moveBall();
}
And in my ball class, where I want the values of the trackbar to be used:
// Declaring the variables for Ball Speed in X and Y coordinates
private int xSpeed, ySpeed;
public Ball()
{
//... Other code
xSpeed = Form1.ranNum.Next(1, 20);
ySpeed = Form1.trackBarValue; // <- An example of what I was hoping to use in my code.
}
public void moveBall()
{
ballRec.X += xSpeed;
ballRec.Y -= ySpeed;
}
When I run my code as it is, the xSpeed
works perfectly (as expected) however the trackBarValue
from the trackbar is not being recognised.
The current properties of my trackbar include:
and it's vertical (not that it matters).
How do I gather the values from the trackbar and use them in this ball class? I've made a smaller program that just displays the values of the trackbar in a label every time you move the trackbar but I cannot seem to apply this knowledge into the program above.
First of all you're setting the value of ySpeed only when the ball is created, it should work if your ball is fastly disposed, but if you're specting it to change its ySpeed value everytime your TrackBarSpeed scrolls then you're going to have some problems. The easier way o solve your problem is to instead of using a field for ySpeed you use a getter property like so
private int xSpeed;
private int ySpeedMod; // we have the direction variable here -1 or 1 so everytime you want to change the direction you change this variable
private int ySpeed {
get { return Form.trackBarValue * ySpeedMod; }
}
like that everytime you reference you ySpeed it will evaluate the get{} Code so it will bring the last value of Y this happens because int is an struct(value) and not a class(reference) so after you set its value it'll rely on that value given in the specific time