Unable to get a laser for firing at 2D space invaders such as a game

I recently worked on Space Invaders as a game to help me improve my programming skills. I ran into a few problems. I’ve been exploring for several days how you are going to make laser fire on keyUp.

This is my attempt; I can make the laser shoot, but he came across me, why the laser does not continue to move 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 greatly appreciated.

+6
c #
source share
2 answers

The problem is that at each iteration of the loop you reset the y-position of the bullet by writing laserFired = spriteY;

However, once this is fixed, you will encounter another problem: the while loop, which moves the laser bullet, runs only in the laserFire method. It means that:

  • As the laser bullet moves, nothing else can move (because the loop only moves the laser)

  • As soon as the laser bullet stops moving, it will no longer start moving (because you cannot return to the loop without calling laserFire() again.

You should have one game loop that moves everything in your game, instead of having one cycle for each moving object.

+3
source share

Your timer handler simply reduces fireTimer to zero. What motivates re-rendering of the laser? Something needs to be laserFire to re-render the laser. Perhaps you wanted to call laserFire from bulletTimer_Tick ?

0
source share

All Articles