2

我正在制造太空侵略者,我希望我的子弹从我的大炮所在的位置出来。当我按空格键时,子弹会发射,但我每次按空格键时都需要它能够访问我的 cannonX 的位置,它不允许我访问它的信息。

    public void tsbtnStart_Click(object sender, EventArgs e)
    {

        // Make invader

            Invader invaderX = new Invader();
            pnlBattleField.Controls.Add(invaderX);

        // Mke UFO

            Ufo ufoX = new Ufo();
            pnlBattleField.Controls.Add(ufoX);


        // Make cannon
            Cannon cannonX = new Cannon(this.pnlBattleField.Height - 80);

        if (made == false)
        {
            pnlBattleField.Controls.Add(cannonX);
            made = true;

        }
        Point location = cannonX.PointToScreen(Point.Empty);


        tmrClock.Interval = 200;
        tmrClock.Start();
        tmrClock2.Interval = 100;
        tmrClock2.Start();
    }

    public void Form1_KeyPress(object sender, KeyPressEventArgs e)
    {

        if (e.KeyChar == (char)Keys.Space)
        {

            Bullet bulletX = new Bullet(this.pnlBattleField.Height - 80, location.x );
            // "location does not exist in current context

            pnlBattleField.Controls.Add(bulletX);
        }

    }
4

2 回答 2

0

location并且cannonX是 中的局部变量tsbtnStart_Click,因此一旦tsbtnStart_Click返回它们就不再存在。使它们成为您的类的属性,以便它们将持续存在并可以在Form1_KeyPress其他方法中访问。

于 2013-04-23T16:57:09.550 回答
0

好吧,你声明

Point location = cannonX.PointToScreen(Point.Empty);

在你的方法中:

public void tsbtnStart_Click(object sender, EventArgs e)

您需要在开始时在类成员中声明此位置。之后,您将用正确的值覆盖他的值。

像这样:

private Point location = new Point();
location = cannonX.PointToScreen(Point.Empty); // in your method
于 2013-04-23T16:59:00.600 回答