【问题标题】:WinFrame App C# game design: Moving pictureboxes left and rightWinFrame App C# 游戏设计:左右移动图片框
【发布时间】:2017-02-24 23:59:42
【问题描述】:

我希望我的图片框左右移动,到目前为止,它们只会向右移动并在到达边缘时消失。代码中有3个敌人,他们都可以向右移动,当他们撞到“墙”时我怎样才能让它们向左移动?玩家可以双向移动。

{
Random _random;


public MainWindow()
{
    InitializeComponent();
    _random = new Random();
}

private void MainWindow_Load(object sender, EventArgs e)
{

    Size s = new System.Drawing.Size(800, 600);
    this.ClientSize = s; 
    this.FormBorderStyle = FormBorderStyle.FixedSingle;
}

private void MainWindow_KeyDown(object sender, KeyEventArgs e)
{
    {
        if (e.KeyCode == Keys.Left)
        {
            Player.Left -= 20;
        }

        if (e.KeyCode == Keys.Right)
        {
            Player.Left += 20;
        }

    }
}

private void timer1_Tick(object sender, EventArgs e)
{
    int z = _random.Next(0, 10);
    int x = _random.Next(0, 20);
    int y = _random.Next(0, 30);
    LargeEnemy.Left += z;
    MediumEnemy.Left += x;
    SmallEnemy.Left += y;

}

【问题讨论】:

  • 我编辑了我的答案,它适用于图片框

标签: c# winforms visual-studio picturebox


【解决方案1】:

使用我制作的代码,首先制作 3 个全局布尔值:bool LargeGoLeft = true, MediumGoLeft = true, SmallGoLeft = true;
然后像这样将代码放入您的计时器中:

    bool moveLeft = false;
    public Form1()
    {
        InitializeComponent();
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        if((pictureBox1.Left + pictureBox1.Width) >= this.Width)
        {
            moveLeft = true;
        }
        if(pictureBox1.Left < 0)
        {
            moveLeft = false;
        }
        if(moveLeft)
        {
            pictureBox1.Left -= 15;
        }
        if (!moveLeft)
        {
            pictureBox1.Left += 15;
        }
    }

这是我能够测试的版本,它与图片框完美配合

【讨论】:

  • 感谢您的回答,到目前为止对我来说还没有成功。这部分: if ((LargeEnemy.Left + LargeEnemy.Width) >= MainWindow.Width) { LargeGoLeft = false;给我以下错误:非静态字段、方法或属性“control.width”需要对象引用
  • 你的敌人没有宽度? if else 只留下 + 宽度部分并做 + 50 左右(如果你知道宽度就输入它)
  • 这是朝着正确方向迈出的一步。我只需要弄清楚为什么他们都向左走,当只有一个敌人撞到墙上时,他们有不同的速度和大小。
  • 使用 3 个布尔值而不是 1 个
  • 非常感谢!真的很感激。这对我帮助很大。下次我想移动图片框时,我会记住所有这些!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多