首页 > 解决方案 > Winform需要顶部和底部PictureBox的碰撞

问题描述

我有一个大的红色盒子和一个蓝色盒子需要相互碰撞,盒子的左右反弹就好了。但是对于顶部和底部的盒子,我想不出我需要编写哪些正确的代码才能让它发生碰撞。我可以使用另一个代码,但它会反弹到它的来源而不是备用方向。所以我解决了这个问题。我只需要知道它将如何工作。任何帮助将不胜感激。

编辑:事实证明,由于在 Y 轴上使用 player.Bounds.Intersectswith 在第一个计时器上发生冲突,我必须使用第二个计时器才能工作。我得到了我想要的输出。

int enemyL = -10;
int enemyT = 10;
int playerL = 30;
int playerT = -30;

private void mainTimer_Tick(object sender, EventArgs e)
{
    //player.Left += playerL;
    player.Top += playerT;
    //enemy.Left += enemyL;
    enemy.Top += enemyT;

    if (player.Left < 1 || player.Left + player.Width > ClientSize.Width - 2 || (player.Bounds.IntersectsWith(enemy.Bounds)))
    {
        playerL = -playerL;
    }

    if (player.Top < 1 || player.Top + player.Height > ClientSize.Width - 2)
    {
        playerT = -playerT;
    }

    if (enemy.Left < 1 || enemy.Left + enemy.Width > ClientSize.Width - 2 || (enemy.Bounds.IntersectsWith(player.Bounds)))
    {
        enemyL = -enemyL;
    }

    if (enemy.Top < 1 || enemy.Top + enemy.Height > ClientSize.Width - 2)
    {
        enemyT = -enemyT;
    }

标签: c#winformscollisionpicturebox

解决方案


推荐阅读