所以我正在努力做一个迷你塔式防御"游戏。 现在,我目前的问题是我无法将我的图片框带到"拍摄"一个矩形"子弹"
我在开始时声明这些变量
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,我有(只包括Keys.Space,因为其他的是无关紧要的。
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(显然是形式)
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);
}
一切正常,当我按空间并移动"塔" (图片框)到任何一边,矩形将在那里。 但这是问题
我的想法是使用timer_tick移动Bullet,代码如下所示。它应该在每个计时器滴答时移动子弹-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;
}
}
TL; DR矩形只是"消失"甚至坐标也告诉它应该在图片框上方的屏幕上向上移动。
我真的不知道为什么会这样,并且已经尝试了很多东西。
这里的完整代码http://pastebin.com/WVpLzxUT(如果您想要更好地查看它)
答案 0 :(得分:0)
如果Bullet
是Rectangle
并且您希望在每个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)更好地命名,例如bulletIsActive和2)使用它拥有的数据类型bool
:if (bulletIsActive)