Click here to Skip to main content
12,549,230 members (45,149 online)
Rate this:
Please Sign up or sign in to vote.
See more: C#
I built this simple cannon game, well the problem is my mousedown event that is responsible for shooting projectile doesn't work....
Help me please!

You can download the game here[^]

   public partial class Form1 : Form
        const int SCREEN_WIDTH = 600;
        const int SCREEN_HEIGHT = 480;
        const int PROJECTILE_SPEED = 1;
        const int BASE_TARGET_SPEED = 8;
        const float COLLISION_DISTANCE = 20.0f;
        const int STARTING_LIVES = 3;
        const int GAME_DIFFICULTY_CONTROL = 3;
        const int LIVES_TILE_WIDTH = 16;
        int targetVelocityX;
        int targetVelocityY;
        Random random;
        bool isGameRunning = false;
        int lives;
        int level;
        public Form1()
            this.ClientSize = new Size(SCREEN_WIDTH,SCREEN_HEIGHT);
            random = new Random();
        #region events

        private void Form1_Load(object sender, EventArgs e)
            TitleScreen.Top = 0;
            TitleScreen.Left = 0;
            TitleScreen.Width = SCREEN_WIDTH;
            TitleScreen.Height = SCREEN_HEIGHT;
        private void Form1_MouseMove(object sender, MouseEventArgs e)
            Player.Left = e.X - Player.Width/2;
            Player.Top = SCREEN_HEIGHT - Player.Height;
        private void GameUpdateTimer_Tick(object sender, EventArgs e)
            Projectile.Top -= PROJECTILE_SPEED;
            Target.Top += targetVelocityY;
            Target.Left += targetVelocityX;
        private void Form1_MouseDown(object sender, MouseEventArgs e)


        #region gameplay methods

        private void BeginGame()
            isGameRunning = true;
            lives = STARTING_LIVES;
            level = 1;
        private void EndGame()
            isGameRunning = false;
        private void KillPlayer()
            if (lives == 0)
        private void KillTarget()
        private void DisplayLives()
            LivesDisplay.Width = lives * LIVES_TILE_WIDTH;
        private void FirePorjectile()
            if (Projectile.Bottom < 0)
                Projectile.Left = Player.Left + Player.Width / 2 - Projectile.Width / 2;
                Projectile.Top = Player.Top - Projectile.Height;
        private void ResetPorjectile()
            Projectile.Top = -Projectile.Height;
        private void ResetTarget()
            targetVelocityX = random.Next(2,6);
            targetVelocityY = BASE_TARGET_SPEED + level/ GAME_DIFFICULTY_CONTROL ;
            if (random.Next(2) == 0)
                targetVelocityX *= -1;
            Target.Top = -Target.Height;
            Target.Left = SCREEN_WIDTH / 2 - Target.Width / 2;

        #region collision methods

        private void CheckGroundCollision()
            if (Target.Bottom > SCREEN_HEIGHT)
        private void CheckAirCollision()
            Point projectileCenter = GetCenter(Projectile);
            Point targetCenter = GetCenter(Target);
            if (Distance(projectileCenter, targetCenter) < COLLISION_DISTANCE)

        #region utility methods

        private Point GetCenter(Control c)
            return new Point(c.Left + c.Width/2,c.Top + c.Height/2);
        private float Distance(Point pointA, Point pointB)
            int a = pointA.X - pointB.X;
            int b = pointA.Y - pointB.Y;
            float c = (float)Math.Sqrt((a * a) + (b*b));
            return c;


Design class

partial class Form1
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.IContainer components = null;
    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing)
        if (disposing && (components != null))
    #region Windows Form Designer generated code

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
        this.components = new System.ComponentModel.Container();
        this.Player = new System.Windows.Forms.PictureBox();
        this.Target = new System.Windows.Forms.PictureBox();
        this.Projectile = new System.Windows.Forms.PictureBox();
        this.GameUpdateTimer = new System.Windows.Forms.Timer(this.components);
        this.LivesDisplay = new System.Windows.Forms.PictureBox();
        this.TitleScreen = new System.Windows.Forms.PictureBox();
        // Player
        this.Player.Location = new System.Drawing.Point(92, 12);
        this.Player.Name = "Player";
        this.Player.Size = new System.Drawing.Size(32, 32);
        this.Player.TabIndex = 0;
        this.Player.TabStop = false;
        // Target
        this.Target.Enabled = false;
        this.Target.Location = new System.Drawing.Point(92, 106);
        this.Target.Name = "Target";
        this.Target.Size = new System.Drawing.Size(32, 32);
        this.Target.TabIndex = 1;
        this.Target.TabStop = false;
        // Projectile
        this.Projectile.Enabled = false;
        this.Projectile.Location = new System.Drawing.Point(137, 200);
        this.Projectile.Name = "Projectile";
        this.Projectile.Size = new System.Drawing.Size(9, 9);
        this.Projectile.TabIndex = 2;
        this.Projectile.TabStop = false;
        // GameUpdateTimer
        this.GameUpdateTimer.Enabled = true;
        this.GameUpdateTimer.Interval = 16;
        this.GameUpdateTimer.Tick += new System.EventHandler(this.GameUpdateTimer_Tick);
        // LivesDisplay
        this.LivesDisplay.Location = new System.Drawing.Point(4, 4);
        this.LivesDisplay.Name = "LivesDisplay";
        this.LivesDisplay.Size = new System.Drawing.Size(48, 16);
        this.LivesDisplay.TabIndex = 3;
        this.LivesDisplay.TabStop = false;
        // TitleScreen
        this.TitleScreen.Enabled = false;
        this.TitleScreen.Location = new System.Drawing.Point(172, 68);
        this.TitleScreen.Name = "TitleScreen";
        this.TitleScreen.Size = new System.Drawing.Size(100, 50);
        this.TitleScreen.TabIndex = 3;
        this.TitleScreen.TabStop = false;
        // Form1
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(284, 262);
        this.Enabled = false;
        this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
        this.MaximizeBox = false;
        this.Name = "Form1";
        this.Text = "Form1";
        this.Load += new System.EventHandler(this.Form1_Load);
        this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseDown);
        this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseMove);
Posted 28-Dec-12 7:56am
Updated 29-Dec-12 9:31am
Sergey Alexandrovich Kryukov 28-Dec-12 14:00pm
Does not work means... what?
Does the mouse works on laptop? Does the game works on other computers?
DaSasha 28-Dec-12 14:15pm
Hi, i have a laptop trackpad( not sure if it makes a difference). I did connect mouse to see if it would fix the problem and it didn't.
Sergey Alexandrovich Kryukov 28-Dec-12 14:46pm
It should not make any difference, especially to your code, but you can always check up by connecting a real mouse to the notebook.
In such cases, I sometimes say: "If you out of clever ideas, try a stupid one". Believe or not, sometimes it worked for me. :-)
Sergey Alexandrovich Kryukov 28-Dec-12 14:51pm
You got an "answer" in Solution 1 suggesting that you might not have a handle in place. You did not answer if it works for you on other computers, but I assume it does (otherwise the question would not make any sense at all). Your problem is that the application works on one computer and does not on another, is that right?

But in general, you should better provide smaller code sample but complete. Yes, you should develop a short but complete sample specially in order to ask a question. First, chances are, you will find the solution by yourself while trying to reproduce the problem. And you can really reveal the problem only on complete code. What's incomplete in yours? You don't show how you add an event handler to the invocation list of a event. You should show all your '+=' operators.

Oh, I see them now, thank you...

where did you
Sergey Alexandrovich Kryukov 28-Dec-12 17:50pm
Did what? :-)
lol i was trying to say " where did you go?"
Sergey Alexandrovich Kryukov 28-Dec-12 18:04pm
Could you be more specific? Use English. Or Russian, maybe... "lol", aha... :-)
lol, you said to upload design class, and so i did. I am guessing you wanted to take a look at it. I just want to figure out whats wrong with my game.
Sergey Alexandrovich Kryukov 28-Dec-12 18:19pm
I see, thank you...
Sergey Alexandrovich Kryukov 28-Dec-12 18:32pm
OK, the event handlers are added correctly, so it's hard to see what's wrong without debugging. And the debugging on my site won't be possible, because Player, Target, Projectile, LiveDisplay and TitleScreen are defined somewhere else. Sorry.

Now, let me ask you straight. Suppose you load the code and set the break points one the following lines:
1) this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseDown);
2) this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseMove);

3) First line of the body of Form1_MouseMove(object sender, MouseEventArgs e)
4) First line of the body of GameUpdateTimer_Tick(object sender, EventArgs e)

Now what? (1) and (2) are reached, but (3) or (4) are not? did you try it exact this way?
And I still did not here from you: is there one computer where everything works. Yes or no? Did you try under debugger on either of the computers?

Now, what's really bad in you code is the use of the timer, especially System.Windows.Forms.Timer. If should never be done. Your best bet is to use thread. As to this particular type of the timer, it's the simplest to use, but not it's just of bad accuracy: it has no accuracy at all...


Я в данный момент в ресторане, я когда вернусь обязательно сделаю то что вы сказали. Also the player,projectile, object pictures are in bin folder.
Sergey Alexandrovich Kryukov 28-Dec-12 18:53pm
OK. You will find end, I believe... Good appetite.
Alright , so i put the break points (1) is reached while (2) is not. But if I click stepinto(f11) then it reaches (2).
But it still doesn't work
Sergey Alexandrovich Kryukov 29-Dec-12 20:34pm
F11 on what line? A hardware event handler should never be reached through a call from withing application. Find where you call it (there is a tool in VS context menu "Find all references" or something) — it should not be called.
Anyways, i changed from event mousedown to mouseup and it worked =)
Thx for your help, and i will take look in to the threads
also yes I have only 1 computer which is my laptop
DaSasha 28-Dec-12 15:03pm
Ok, I do not have an ability to test it on other computer. So if you had a same problem like me you would create small program just to test this problem out, but how else would you test it out?
Also I did add a download link for the program, you can test it out( I know , its insecure to download somebodies code from online, so its your call)
I will add the class so you can see all the += operators.

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

Not sure if your not hitting your MouseDown event or the mousedown event isn't working when your in it but there is an order behind what occurs first.

Here is a link to reivew the process of mousedown that might help:[^]

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web02 | 2.8.161021.1 | Last Updated 30 Dec 2012
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100