【问题标题】:Find collision areas on the picturebox, windows forms在图片框、窗体上查找碰撞区域
【发布时间】: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) 方法来确定桨上的一些相对位置,但我仍然无法实现我想要做的事情。我很困惑现在如何进行。

简而言之,我必须确定球击中球拍时球拍的部分,以便为球提供所需的角度运动。

任何帮助将不胜感激。谢谢。

【问题讨论】:

标签: c# winforms c#-4.0


【解决方案1】:

假设球是pictureBox2 左边的桨是pictureBox1...

在这种情况下,您必须检查pictureBox1.RightpictureBox2.Left .

代码示例:

if (pictureBox1.Right == pictureBox2.Left)
{
    //Collision
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-03
    • 2014-10-14
    • 2016-11-06
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 2015-03-03
    相关资源
    最近更新 更多