矩形应该在屏幕上移动,但却消失了

本文关键字:移动 消失了 屏幕 | 更新日期: 2023-09-27 18:07:29

所以我尝试着做一款迷你的"塔防"游戏。现在,我当前的问题是,我不能让我的图片框"拍摄"一个矩形的"子弹"

我在开头声明了这些变量

    Rectangle Bullet = new Rectangle(225, 400, 10, 25); //position of this shouldn't matter since it's not drawed instantly and it's later moved moved under the picturebox.
    private bool bulletIsActive = false;
    private int update_speed = 250;

同时,定时器声明为AFTER InitializeComponent();

        InitializeComponent();
        timer1.Interval = update_speed;
        timer1.Start();

我有Eventhandler按键,在那里我有(只包括键。空间,因为其他的都不相关。

private void Paaikkuna_KeyDown(object sender, KeyEventArgs e)
    {
            case Keys.Space:
                if(bulletIsActive == false)
                {
                    bulletIsActive = true; //set bool bullet to true and draw the bullet
                    Bullet.Location = new Point(playerX, playerY); //set bullet location at picturebox
                }
                break;
然后是Paaikkuna_paint (form)
private void Paaikkuna_Paint(object sender, PaintEventArgs e)
    {
        if(bulletIsActive == true) //if bulletIsActive == true (Which happens when I press space, draw bullet)
        {
             e.Graphics.DrawRectangle(Pens.Blue, Bullet); 
        }

这一切都很好,当我按空格键并移动"塔"(picturebox)到任何一边时,矩形将在那里。但问题就在这里

我的想法是移动子弹使用timer_tick,代码看起来像这样。它应该移动子弹-10Y每一个计时器滴答,但不是这样,它只是消失了。

        private void timer1_Tick(object sender, EventArgs e)
    {
        int bulletY = Bullet.Location.Y;
        int bulletX = Bullet.Location.X;
        if (bulletY>-10 && bulletIsActive == true) //checks if Bullet.Location.Y is >-10 (if not, it's not on screen and it can be "killed") and also if bullet == true
        {
            Bullet.Location = new Point(bulletX, bulletY - 10);
        }
        else
        {
            bulletIsActive = false;
        }
    }
这个矩形只是"消失"了,即使坐标告诉它应该在屏幕上向上移动,就在图片框的上方。

我真的不知道为什么会这样,我已经尝试了很多方法。

完整的代码在这里http://pastebin.com/WVpLzxUT(如果你想更好地看看它)

矩形应该在屏幕上移动,但却消失了

如果BulletRectangle,并且您希望将其绘制在每个Tick上的新坐标上,则需要将Invalidate绘制在Control上:

private void timer1_Tick(object sender, EventArgs e)
{
    int bulletY = Bullet.Location.Y;
    int bulletX = Bullet.Location.X;
    //checks if Bullet.Location.Y is >-10 
    //(if not, it's not on screen and it can be "killed") 
    //and also if bullet == true
    if (bulletY > -10 && bullet == true) 
    {
        Bullet.Location = new Point(bulletX, bulletY - 10);
        Paaikkuna.Invalidate();   // <-- trigger the paint event!
    }
    else
    {
        bullet = false;
    }
}

Btw:而不是if (bullet == true)你应该1)命名它更好,说,子弹tisactive和2)利用数据类型bool它有:if (bulletIsActive)