最近,我一直在从事太空侵略者之类的游戏,以帮助我提高编程技能。我陷入了一些问题。我已经研究了几天,关于如何在keyUp上进行激光发射。
到目前为止,这是我的尝试;我可以让激光发射,但令我迷惑的是,为什么激光不会继续向上移动...
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace SpaceInvaders
{
public partial class Form1 : Form
{
public int spriteX = 226;
public int spriteY = 383;
bool bulletFire = false;
int fireTimer = 8;
int laserFired;
public Form1()
{
InitializeComponent();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
public void laserFire()
{
//on laser fire i wont the bulle to move up while bullet timer is enabled
//moving up slowly with set intervals
while (bulletTimer.Enabled == true)
{
PictureBox laser = new PictureBox();
laser.BackColor = Color.Chartreuse;
laser.Width = 5;
laser.Height = 30;
laserFired = spriteY;
laserFired = laserFired - 10;
this.Controls.Add(laser);
laser.Location = new Point(spriteX, laserFired);
}
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
//Fire bullet
if (e.KeyCode == Keys.Up)
{
bulletFire = true;
if (bulletFire == true)
{
laserFire();
bulletTimer.Enabled = true;
}
}
//Controls Right movement
if (spriteX <448)
{
if (e.KeyCode == Keys.Right)
{
spriteX = spriteX + 20;
}
}
//Controls Left Movement
if (spriteX > 0)
{
if (e.KeyCode == Keys.Left)
{
spriteX = spriteX - 20;
}
}
//Points sprite to new location
pctSprite.Location = new Point(spriteX, spriteY);
}
private void bulletTimer_Tick(object sender, EventArgs e)
{
if (fireTimer == 0)
{
bulletTimer.Enabled = false;
}
else { fireTimer = fireTimer - 1; }
}
}
}
帮助或建议将不胜感激谢谢。
最佳答案
您遇到的问题是,在循环的每次迭代中,都需要通过编写laserFired = spriteY;
来重置项目符号的y位置
但是,一旦纠正,就会遇到另一个问题:仅在laserFire
方法中执行移动激光子弹的while循环。这意味着:
laserFire()
,您将无法回到循环中。)您需要有一个游戏循环来移动游戏中的所有内容,而不是每个移动物体都有一个循环。
关于c# - 无法像游戏一样在2D太空入侵者中发射激光,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4117358/