C#在使用ref in方法的简单2D游戏中缺乏切割

时间:2017-01-07 18:42:13

标签: c# graphics2d

我尝试创建2D马里奥风格的游戏。一切顺利,直到我开始使它更“客观”.Mario不会停在窗口结束 - 停止但是在经过窗口之后。如果我制作没有参考的方法,马里奥甚至不会停下来。

马里奥班

class Mario: System.Windows.Forms.PictureBox
{
    public Mario(int x, int y)
    {
        Image = Image.FromFile("Mario.png");
        Location = new Point(x, y);
        Size = new Size(16, 32);
        SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
        TabIndex = 0;
        TabStop = false;
    }
public void colision( System.Windows.Forms.Panel s,ref bool l, ref bool r)
    {
        if (this.Right > s.Right) { r = false; }

        if (this.Left < s.Left) {  l = false;  }
    }

}

主要课程 - Form1

 public partial class Form1 : Form
{

    bool right=false,left=false;

public Form1()
    {
        InitializeComponent();
        player.Top = screen.Height - player.Height;
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        if(right== true) { player.Left += 1; }
        if (left == true) { player.Left -=1; }

       player.colision(screen, ref left, ref right);
}

屏幕是System.Windows.Forms.Panel,播放器是Mario Type,它是在form1.Designer.cs中初始化的

我删除了不相关的字段和方法。

1 个答案:

答案 0 :(得分:1)

控件的位置与其父级相关 - 如果您将Mario放在(0, 0),则它不会出现在您的<\ n左上角< em> screen 或 form ,但在Panel的左上角 - 它的直接父级。

同样,Panel的位置也与其父级相关。

我们假设您的Panel位于(100, 100)的表单中,其大小为(400, 300) - 这意味着其Left属性为{{1}它的100属性为Right - 500对于那100个像素将无法看到。

所以你的检查应该是:

Mario

您已经使用垂直展示位置做了正确的事情(使用if (this.Right > s.Width) { r = false; } if (this.Left < 0) { l = false; } 代替Height):

Bottom