[英]Using the value of trackbar as a variable for another class
我想为正在使用VS2013中的Winforms的游戏使用轨迹栏。
这个想法是,用户应该选择使用轨迹栏移动球的速度(将轨迹栏中的值用于不同类中的另一个变量)。
这是我目前拥有的代码:
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();
}
在我的Ball类中,我希望使用轨迹栏的值:
// 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;
}
当我按原样运行代码时, xSpeed
可以完美运行(按预期方式),但是无法识别trackBarValue
。
我的跟踪栏的当前属性包括:
而且它是垂直的(无关紧要)。
如何从轨迹栏中收集值并将其用于本球类? 我编写了一个较小的程序,每次您移动跟踪栏时,它只会在标签中显示跟踪栏的值,但是我似乎无法将此知识应用到上面的程序中。
首先,仅在创建球时才设置ySpeed的值,如果快速放置球,它应该可以工作,但是如果您希望每次TrackBarSpeed滚动时更改它的ySpeed值,那么您将有一些问题。 解决问题的更简单方法是使用getter属性,而不是使用ySpeed字段
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; }
}
像这样,每次您引用ySpeed时,它将评估get {}代码,因此它将带来Y的最后一个值,因为int是struct(value)而不是class(reference),因此在设置其值之后,它将依靠在特定时间内给出的值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.