Recently I've been working on a Space Invaders like game, to help me boost my programming Skills. I've fallen into a few problems. I've been researching for a few days now, in how you would go about making a laser fire, on keyUp.
This is my attempt so far; I can get the laser to fire, but it has stumbled me why the laser doesn't carry on moving up...
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; }
}
}
}
Help or advice would be much appreciated thanks.
The problem you have is that on every iteration of the loop, you reset the y position of the bullet by writing laserFired = spriteY;
However, once that is corrected, you will run into another problem: the while loop that moves the laser bullet is only executed in the laserFire
method. This means that:
While the laser bullet moves, nothing else can move (because the loop only moves the laser)
Once the laser bullet stops moving, it will never start moving again (because you cannot go back into the loop without calling laserFire()
again.
You need to have a single game loop that moves everything in your game, instead of having one loop for every moving object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With