【发布时间】:2018-05-14 09:09:22
【问题描述】:
我是 C# 的新手,我正在尝试用 C# 构建一个乒乓球游戏,到目前为止,我已经能够使用计时器功能在我的窗体面板内实现球的角运动,如下所示:
System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
System.Windows.Forms.Timer timer2 = new System.Windows.Forms.Timer();
public Form1()
{
InitializeComponent();
radians = (Angle(_start, _end) - 180) * -1;
isFirstTime = true;
timer.Interval = 25;
timer.Tick += Timer_Tick;
timer.Start();
}
private void Timer_Tick(object sender, EventArgs e)
{
middle.X -= Convert.ToInt16(interval * Math.Cos(radians));
middle.Y -= Convert.ToInt16(interval * Math.Sin(radians));
pictureBox2.Location = middle;
//pictureBox1 is the paddle and pictureBox2 is the ball....
if (IsTouching(pictureBox2, pictureBox1)) //Custom method to check whether the two picture boxes touch each other.
{
double relativeLocation = Math.Abs(((double)panel1.Left - (double)pictureBox2.Left) / (double)pictureBox2.Width);
timer.Stop();
timer2.Interval = 25;
timer2.Tick += Timer2_Tick; }
timer2.Start();
}
}
private void Timer2_Tick(object sender, EventArgs e)
{
isFirstTime = false;
middle.X += Convert.ToInt16(interval * Math.Cos(radians));
middle.Y += Convert.ToInt16(interval * Math.Sin(radians));
pictureBox2.Location = middle;
if (pictureBox2.Left < panel1.Left)
{
timer2.Stop();
timer.Start();
}
}
这只是我项目的开始,是的,这段代码中也会有很多问题,但目前我面临的问题是,当球击中球拍时,我需要确定球拍是否在球拍的哪一侧球已经击中,在右侧或左侧或可能在中心,据此我必须设置球的角度运动,如果球击中桨的右侧,则右侧运动,左侧桨的左侧移动,中间部分水平向上。
我尝试使用double relativeLocation = Math.Abs(((double)panel1.Left - (double)pictureBox2.Left) / (double)pictureBox2.Width) 方法来确定桨上的一些相对位置,但我仍然无法实现我想要做的事情。我很困惑现在如何进行。
简而言之,我必须确定球击中球拍时球拍的部分,以便为球提供所需的角度运动。
任何帮助将不胜感激。谢谢。
【问题讨论】:
-
只添加一次事件处理程序。您在第一个计时器的每个滴答声上添加第二个滴答声处理程序,因此它在每个滴答声上多次运行该代码。