Chaaachuii
Chaaachuii

Reputation: 3

how to shoot continuously while pressing spacebar in c# windows form?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Don_tgetthatcincp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        void shoot() //shoot funtion
        {
            bullet.Left += 50;
            if (bullet.Left > 50)
            {
                bullet.Image = Properties.Resources.bullet;
            }
        }

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            while (e.KeyCode == Keys.Space)
            {
                shoot();
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            shoot();
        }
    }
}

I'm creating a simple shooting game using windows form in c# but the problem is, my game only shoot once when i run it. everytime i hit the spacebar it doesn't produce bullet. Can you help me out? thankyou. here's mycode.

Upvotes: 0

Views: 134

Answers (1)

jmcilhinney
jmcilhinney

Reputation: 54417

You are calling shoot in the Tick event handler but you never Start the Timer, so that Tick event is never raised.

You should be starting the Timer on KeyDown and stopping it on KeyUp. I also just realised that you had a while loop rather than an if statement, which doesn't make sense:

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Space)
    {
        shoot();
        timer1.Start();
    }
}

private void timer1_Tick(object sender, EventArgs e)
{
    shoot();
}

private void Form1_KeyUp(object sender, KeyEventArgs e)
{
    timer1.Stop();
}

EDIT:

Further to that, the shoot method doesn't actually do what I expected it would. It doesn't actually shoot but rather just moves the bullet tot he right. At no point in that code do you create another bullet or reset the existing bullet to the left. It seems to me that this is the sort of code you end up with when you write it without actually knowing what it's supposed to do. If you only want one bullet at a time then you need to rest its Left back to zero when it hits something or leaves the screen. If you want multiple bullets then you need to some way to handle that. There's no one way some I can't just tell you how to do it.

Upvotes: 1

Related Questions