How to make the button start the game? - c#

I'm currently making my first game, a simple iteration of Pong. I want to have it so that a button can be pressed and this starts the timer, however when I add the button to the game, I find that the game loses the ability to be controlled.
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 pong_200
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
bool moveup;//This is a boolean to detect when player's up.
bool movedown;//This is a boolean to detect when player's down.
int speed = 5;//Integer that holds a generic value of 5.
int posx = 5;//Speed of ball horizontally.
int posy = 5;//Speed of ball vertically.
int playerPoints = 0;//Player's score
int cpuPoints = 0;//Computer's score
private void keypressdown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Up)
{
moveup = true;//If the player presses up, the boolean changes to true.
}
if (e.KeyCode == Keys.Down)
{
movedown = true;//If the player presses down, the boolean changes to true.
}
}
private void keypressup(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Up)
{
moveup = false;//If the player lets go of up, the boolean changes to false.
}
if (e.KeyCode == Keys.Down)
{
movedown = false;//If the player lets go of down, the boolean changes to false.
}
}
private void timerTick(object sender, EventArgs e)//This event occurs every 20 m/s.
{
playerScore.Text = "" + playerPoints;//Displays the player's score on the playerScore label.
aiScore.Text = "" + cpuPoints;//Displays the computer's score on the cpuScore label.
ball.Top -= posy;//Sets the top of the ball to Y.
ball.Left -= posx;//Sets the left side of the ball to X.
aiPaddle.Top += speed;//Sets the CPU as the maximum speed integer.
if (playerPoints < 5)//If the score is lower than 5...
{
if (aiPaddle.Top < 0 || aiPaddle.Top > 455)
{
speed = -speed;
} //If the computer has reached the top or bottom of the frame, change the direction back into the frame.
}
else
{
aiPaddle.Top = ball.Top + 30;//Else if the score is more than 5, let the paddle follow the ball for difficulty.
}
if (ball.Left < 0)//If the ball has gone past the player...
{
ball.Left = 434;//Set the ball back to the middle.
posx = -posx;//Change the direction of the ball.
posx -= 2;//Make the ball's speed faster.
cpuPoints++;//Give the CPU one point.
}
if (ball.Left + ball.Width > ClientSize.Width)//If the ball has gone past the computer...
{
ball.Left = 434;//Set the ball back to the middle.
posx = -posx;//Change the ball direction.
posx += 2;//Speed up the ball.
playerPoints++;//Give the player one point.
}
if (ball.Top < 0 || ball.Top + ball.Height > ClientSize.Height)
{
posy = -posy;//If the ball hits either the top or bottom of the frame, reverse the speed of the ball, to keep it in the screen.
}
if (ball.Bounds.IntersectsWith(playerPaddle.Bounds) || ball.Bounds.IntersectsWith(aiPaddle.Bounds))
{
posx = -posx;//Then bounce the ball in the opposite direction.
}
if (moveup == true && playerPaddle.Top > 0)
{
playerPaddle.Top -= 8;//If the boolean is up, and within the upper bounds, move the player towards the top by 8.
}
if (movedown == true && playerPaddle.Top < 455)
{
playerPaddle.Top += 8;//If the boolean is down, and within the lower bounds, move the player towards the bottom by 8.
}
if (playerPoints > 10)
{
pongTimer.Stop();
MessageBox.Show("You Win!");//If the player has more than 10 points, stop the game timer, and show the victory box.
}
if (cpuPoints > 10)
{
pongTimer.Stop();
MessageBox.Show("You Lose!");//If the computer has more than 10 points, stop the game timer and display the loss box.
}
}
private void button1_Click(object sender, EventArgs e)
{
pongTimer = true;
}
}
}
The game itself works when there is no button, but I would like for the game to be started with a button press as I am broadening the horizons. I would appreciate any help or guidance with this!

just a tought:
When working with games, I like to think/work with scenes.
e.g.
Splash Screens --> Menu --> Game --> Pause --> Credits....
Translated to your problem, maybe you could have a form containing your startbutton, and load the next form containing your game on click.

Related

How do I implement a restart function after game over in my game?

I'm a beginner using Visual Studio to make a C# Windows Form. So I have a brick game (like the classic block game with ball and bricks) where if the player doesn't bounce the ball back, it's basically game over. However when this happens, the timer is just stopped and there's no way to restart. The code I have now just says to create a message box with "You lose" and you have to exit the program to play again. If you reach score 30 then that's a win and to play again you have to exit also.
I've tried googling this and the suggestions I see is if it's all set up already in their cases so implementing it to mine without having to re-do it all in someway is hard. I would like to make a simple implementation (or edit) where there is a play again function. How can I modify existing code to do this? Thank you dearly for any help.
This is the section of code that accounts for game-over if statement.
EDIT= Entire code provided.
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;
using System.Media;
using System.Reflection;
using System.IO;
namespace FinalProjectGame
{
public partial class FrmGame : Form
{
bool goLeft;
bool goRight;
int speed = 10;
int pBallx = 5;
int pBally = 5;
int score = 0;
public FrmGame()
{
InitializeComponent();
}
private void keyisdown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Left && btnGamer.Left > 0)
{
goLeft = true;
}
if (e.KeyCode == Keys.Right && btnGamer.Left + btnGamer.Width < 920)
{
goRight = true;
}
}
private void keyisup(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Left)
{
goLeft = false;
}
if (e.KeyCode == Keys.Right)
{
goRight = false;
}
}
private void TmrMainTimer_Tick(object sender, EventArgs e)
{
pBall.Left += pBallx;
pBall.Top += pBally;
lblScore.Text = "Score: " + score; //keeping score
if (goLeft) { btnGamer.Left -= speed; } //izquierda
if (goRight) { btnGamer.Left += speed; } //derecha
if (btnGamer.Left < 1)
{
goLeft = false; //disables "no-clip"
}
else if (btnGamer.Left + btnGamer.Width > 920)
{
goRight = false;
}
if (pBall.Left + pBall.Width > ClientSize.Width || pBall.Left < 0)
{
pBallx = -pBallx; //left, right wall bounce
}
if (pBall.Top < 0 || pBall.Bounds.IntersectsWith(btnGamer.Bounds))
{
pBally = -pBally; //top, bottom wall bounce
}
foreach (Control x in this.Controls)
//main code brickies subtraction
{
if (x is PictureBox && x.Tag == "blockies")
{
if (pBall.Bounds.IntersectsWith(x.Bounds))
{
this.Controls.Remove(x);
pBally = -pBally;
score++;
} //end of main
//ALT method foreach (Control x in this.Controls)
//{
if (!(x is PictureBox))
continue;
//this is needed if some specific property of the PictureBox is needed.
PictureBox ctl = (PictureBox)x;
if (ctl.Tag.ToString() != "blockies")
continue;
if (!pBall.Bounds.IntersectsWith(ctl.Bounds))
continue;
//this.Controls.Remove(x);
x.Visible = false;
pBally = -pBally;
score++;
//}
}
}//----
//This accounts for user score. Upon completing the game, the user wins. If the user does not capture the ball, it is automatically a game over.
if (score == 30)
{
gameOver();
MessageBox.Show("YES! WINNER!");
}
if (pBall.Top + pBall.Height > ClientSize.Height)
{
gameOver();
MessageBox.Show("SORRY YOU LOSE!");
}
//======
}
private void gameOver()
{
TmrMainTimer.Stop();
}
private void FrmGame_Load(object sender, EventArgs e) //main form load
{
//load the splash screen form that was made with design view
SplashScreen splash = new SplashScreen();
splash.Show();
//using system media to play the audio which is played upon start of the main form
SoundPlayer Sndplayr = new SoundPlayer(Properties.Resources.RoleMusic);
Sndplayr.Play();
}
}
}
If you want to restart that WinForms application, use Application.Restart(). You may close your game form and call restart in your static Main() method afterwards.
private void TmrMainTimer_Tick(object sender, EventArgs e)
{
...
if (pBall.Top + pBall.Height > ClientSize.Height)
{
gameOver();
MessageBox.Show("SORRY YOU LOSE!");
// close the game form
this.Close();
}
}
And in your startup code:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FrmGame());
// restart application
Application.Restart();
}
}
Edit:
The example above ist the easiest way to play that game from start. Of course, there are many other options:
As an extension, you can start your game form from a (maybe hidden) program startup form. If you register an event handler on the FrmGame.FormClosed event, you can restart that form again after the previous game was lost.
As many other guys suggested, a StartAgain() method, that resets your logic, is also an option.
Separate drawing logic (View) from game logic (Controller). For a such a simple game it is not necessary and overkill. But it is always a good idea to keep the things simple and clear. See the MVC pattern for your next project...

Making breakout game

My friends I made some parts of this game but I have two problems in this game.
1)Problem about distinguishing ball collision with obstacles
1-1)A first problem is related to complex guidelines that I used them for simulation of ball collision with board or ball collision with blocks. These guidelines are not accurate especially when the ball meets with block corner or bottom.
If it is not better for collision distinguish I use a better code. I wrote this code. Are you think that are there better way?
2)How I can do a work that if the ball collision with any obstacle, the obstacle report the collision.
My aim is about using of events.
Are you thinking that I make obstacles as runtime?
If I make as a runtime, how I can make collision event for them?
With best regards
private Point MouseDownLocation;
int step = 2;
int stepleft = 2;
bool flagBottom;
bool flagTop;
private void Form1_Load(object sender, EventArgs e)
{
timer1.Interval = 10;
timer1.Enabled = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
ball.Top += step;
ball.Left += stepleft;
//board simulate collision
bool collisonX = ball.Location.X + ball.Width > board.Location.X && ball.Location.X < board.Location.X + board.Width;
bool collisonY = ball.Top + ball.Height == board.Location.Y || ball.Top + ball.Height - 1 == board.Location.Y;
//board2(button1) simulate collision
bool collisonX2 = ball.Location.X + ball.Width > board2.Location.X && ball.Location.X < board2.Location.X + board2.Width;
bool collisonY2 = ball.Top + ball.Height == board2.Location.Y || ball.Top + ball.Height - 1 == board2.Location.Y;
//Collision the ball with under buttons
bool collsionButtonY = ball.Top - ball.Height == board2.Location.Y || ball.Top - ball.Height == board2.Location.Y - 1;
//collision leftwall
bool leftWall = ball.Left == 0 || ball.Left == -1 || ball.Left == 1;
//collision rightwall
bool topWall = ball.Top == 0 || ball.Top == -1 || ball.Top == 1;
bool bottomWall = collisonX && collisonY;
bool toppWall = collisonX2 && collisonY2;
//collision
bool barrier = collisonX2 && collsionButtonY;
//rightwall
bool rightWall = ball.Left + ball.Width == this.ClientSize.Width || ball.Left + ball.Width == this.ClientSize.Width - 1;
// sidewall = collision rightwall or leftwall
bool sideWall = leftWall || rightWall;
//Check the ball hit the ground
bool check = ball.Top + ball.Height < this.ClientSize.Height;
//if topWall true,This means that the ball is hit to the topwall
if (topWall)
{
flagBottom = false;
flagTop = true;
if (stepleft > 0)
{
step = 2;
}
else if (stepleft < 0)
{
step = 2;
}
}
//if bottomWall true,This means that the ball is hit to the board
else if (bottomWall)
{
flagBottom = true;
flagTop = false;
if (stepleft > 0)
{
step = step * -1;
}
else if (stepleft < 0)
{
step = step * -1;
}
}
//if barrier true and flagbottom true,This means that the ball is hit to the board2(button1)
else if (barrier && flagBottom)
{
if (stepleft > 0)
{
step = step * -1;
}
else if (stepleft < 0)
{
step = step * -1;
}
}
//if toppWall true and flagTop true,This means that the ball is hit to The top button is hit
else if (toppWall && flagTop)
{
if (stepleft > 0)
{
step = step * -1;
}
else if (stepleft < 0)
{
step = step * -1;
}
}
else if (sideWall)
{
//if leftwall true,This means that the ball is hit to the left side wall
if (leftWall)
{
if (flagTop)
{
stepleft = 2;
}
else if (flagBottom)
{
stepleft = 2;
}
}
//if rightWall true,This means that the ball is hit to the left side wall
else if (rightWall)
{
if (flagTop)
{
stepleft = -2;
}
else if (flagBottom)
{
stepleft = -2;
}
}
}
//check if ckeck==ture,this mean the ball is hit the ground
else if (!check)
{
timer1.Enabled = false;
}
}
private void board_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
MouseDownLocation = e.Location;
}
}
private void board_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
board.Left = e.X + board.Left - MouseDownLocation.X;
}
}
Define each "Wall" as an Object, this will increase your codes readablility. it will also allow you to define an Event for each wall, Listen to t. that way you know which wall has been hit
N.b. this is pseudo code. It wont compile :P
public class Wall
{
int X,Y,W,H;
//Define an event, add a listener to this, becuase we will fire this when there is a collision
public event EventHandler OnCollision;
public void CollisionCheck(Ball playerBall)
{
//1 Check for a collision with the "Ball" object
if(Ball.Rectangle().Intersects(this.Rectangle))
this.OnCollision(this, EventArgs.Empty); //Fire the event, null check might be requried
}
}
I do not know your game but (suspect 2D brick-like game)
Objects/Obstacles
all objects/obstacles can be simplified to rectangular objects
so make list of them with defined parameters like size and position
if they are movable/dropable then also speed and state...
type of object (affects color,scoring,capabilities...)
create member function like update(dt),draw()
create events you like OnHIt,OnCollision,...
for example (C++ pseudo code):
// game object types ...
enum _game_object_type_enum
{
_game_object_type_none=0,
_game_object_type_wall,
_game_object_type_brick1,
_game_object_type_brick2,
_game_object_type_brick3,
_game_object_type_bomb,
_game_object_type_joker1,
_game_object_type_joker2,
...
};
// game object class
class game_object
{
public;
int type; // type of object
float x,y,vx,vy,hx,hy; // position,speed,half size of rectangle
void update(float dt); // this call periodicaly in some timer updates positions,... and call events, dt is time passed
void draw(); // can add some rendering device context ...
};
// whole game class holds the game world/board/map and player(s) ...
class game_board
{
public;
game_object *go; int gos; // list of all objects in game
void update(float dt) { for (int i=0;i<gos;i++) go[i].update(dt); }
void draw() { for (int i=0;i<gos;i++) go[i].draw(); }
}
events and flow control
first define some events you need
either you use global function/pointers for that or as members
depends on your platform and to what you are used to
for example like this:
void OnCollisionFX(game_object o1,game_object o2)
{
// do something ...
}
void (*OnCollision)(game_object o1,game_object o2)=OnCollisionFX;
for player interactions only (like player controlled object collisions test only)
is better to handle this in game_object::update(dt) but you need to add player context
something like game_object::update(dt,plr)
where plr is pointer to player controlled object or player class
if you have massive interactivity between game objects (like brick/brick collisions)
then is better to handle this in game_board::update(dt)
because otherwise you will need to provide references for everything into update call
and that will quickly lead to heap/stack trashing and very slow performance
also more advanced multiple object collision/interaction approaches are better in main game class
here is an example for first case:
void game_object::update(float dt,game_object &plr)
{
// update position
x+=vx*dt;
y+=vy*dt;
// here you should make your own collision test of coarse
if (fabs(x-plr.x)<=hx+plr.hx)
if (fabs(y-plr.y)<=hy+plr.hy)
{
... do what you need like mirror or stop speed or clamp position ...
if (OnCollision) OnCollision(this,plr);
}
}
in second case you should check each object against each other
void game_board::update(float dt)
{
int i,j;
// update position
for (i=0;i<gos;i++)
{
go[i].x+=go[i].vx*dt;
go[i].y+=go[i].vy*dt;
}
// here you should make your own collision test of coarse
for (i=0;i<gos;i++)
for (j=i+1;j<gos;j++) // the lower indexes are already tested
if (fabs(go[i].x-go[j].x)<=go[i].hx+go[j].hx)
if (fabs(go[i].y-go[j].y)<=go[i].hy+go[j].hy)
{
... do what you need like mirror or stop speed or clamp position ...
if (OnCollision) OnCollision(go[i],go[j]);
}
}
performance
you can improve performance by use of type property
for example if some game objets are static then the do not need to update position
if some are indestructible then there can be also some processing avoided and so on ...
[notes]
dt/fps/speed should be combined
so in each frame your player controlled object or any moving object does not move further
then the half size of smallest object
if this is not true then you need better collision test
use line intersection algorithm
last position and actual position gives you one line
and object edge gives you the other one
if booth objects are moving then that is even more complicated :)

How can I detect the direction of a dragging event?

So I have a PictureBox and the user is supposed to drag the cursor inside it towards the direction shown by the arrow (in the PictureBox), but I'm not sure how I will set the coordinates to make sure the user dragged in the correct direction (up, down, right, or left).
private void picArrow_MouseDown(object sender, MouseEventArgs e)
{
mPointDown = new Point(e.X, e.Y);
//lblTest.Text = "X: " + mPointDown.X.ToString() + " Y: " + mPointDown.Y.ToString();
}
private void picArrow_MouseUp(object sender, MouseEventArgs e)
{
lblTest.Text += " " + " X: " + e.X.ToString() + " Y: " + e.Y.ToString();
//MessageBox.Show("Entered mouseup");
//rnd_Arr refers to the number of the arrow being shown, 0 = towards the right
if (rnd_Arr == 0 && mPointDown.X >= 0 && mPointDown.Y >= 0 && e.X >= 40 && e.Y >= 0)
{
//some code
}
else
{
MessageBox.Show("DONE!");
}
}
And I know this code doesn't work because even if the user drags down (when he's supposed to drag up), it still accepts it and increments the score.
I'm not putting too much restrictions. It doesn't have to be in a perfectly straight line, or start and end in exact locations. As long as the user is dragging inside the PictureBox and dragging to the correct direction, or at least reaches the minimum length to make sure it is considerable that the user is dragging to the correct direction, like for example:
The arrow shown is pointing to the right. The user doesn't have to drag all the way through the arrow, if he drags horizontally past 40px (and the whole length of the arrow is, say, 80px), then that'll add a point to his score. Nevertheless, I'm deliberating this part, if I should just be more demanding and require the user to drag all the way through.
Should I remove the mouse events for the PictureBox and add mouse events for the form instead?
Thank you!
You're going to want to check the MouseDown.X and compare it to the MouseUp.X (or Y if you want to check vertical direction as well). It is important to note that (0, 0) is the upper left of your screen.
Start by subtracting MouseUp.X from MouseDown.X to get a delta X. This is your change in X pixels over the move operation.
If your X comparison yields a negative delta (MouseUp.X is smaller than MouseDown.X), your mouse has moved left.
If your X comparison yields a positive delta (MouseUp.X is larger than MouseDown.X), your mouse has moved right.
The same concept applies to the Y coord, positive change means you moved the mouse down and a negative changemeans you moved the mouse up. See below code:
Point mouseDownPoint;
Point mouseUpPoint;
float deltaX = mouseUpPoint.X - mouseDownPoint.X;
float deltaY = mouseUpPoint.Y - mouseDownPoint.Y;
if (deltaX > 0)
{
// Moved right
}
else if (deltaX < 0)
{
// Moved left
}
if (deltaY > 0)
{
// Moved down
}
else if (deltaY < 0)
{
// Moved up
}
private void picArrow_MouseUp(object sender, MouseEventArgs e)
{
bool movedUp, movedDown, movedLeft, movedRight;
if (e.X == mPointDown.X) { movedRight = movedLeft = false; }
else { movedRight = e.X < mPointDown.X; movedLeft = !movedRight; }
if (e.Y == mPointDown.Y) { movedUp = movedDown = false; }
else { movedUp = e.Y < mPointDown.Y; movedDown = !movedUp; }
// Code can now use the Booleans above as needed
// . . .
}

penalty game in xna, how do I just count 1 goal and then let time for a goal message?

I am programming a penalty shoout game in xna, my question is how do I count just 1 goal and then let time for a goal message??,
I already solve the collison between the goalkeeper, goal and the goal area, and I keep and score but when the ball touched the goal area, the score always increment when the ball touched the goal area, how do I just count 1 goal and then display a goal message??
this is what I have so far, I think about a delay but its not working, please help I am stucked in this
if (_gameState == GameState.Playing)
{
if (CollideGoalArea())
{
if (CollideGoalKeeper())
{
_messageToDisplay = "Goalie defends the goal!";
this.Window.Title = "Missed!";
_gameState = GameState.Message;
}
else
{
score++;
_messageToDisplay = "GOAL!";
this.Window.Title = "Goal!";
_gameState = GameState.Message;
}
}
else
{
_messageToDisplay = "You missed the goal.";
_gameState = GameState.Message;
}
}
else if (_gameState == GameState.Message)
{
if (Mouse.GetState().RightButton == ButtonState.Pressed)
{ // right click to continue playing
_gameState = GameState.Playing;
balonpos.X = 300;
balonpos.Y = 350;
}
}
The problem is happening because your code increments score any time it detects that ball is inside the goal. Since (by default) Update is called 60 times per second, if your ball is inside the goal score will get incremented by 60 every second.
You could rewrite your code so that your game has 2 states: Displaying a message state and playing state:
enum GameState
{
Playing,
Message
}
GameState _gameState = GameState.Playing;
String _messageToDisplay = "";
int _score = 0;
protected override void Update(GameTime gameTime)
{
if(_gameState == GameState.Playing)
{
if(CollideGoalArea())
{
if(CollideGoalkeeper())
{
_messageToDisplay = "Goalie defends the goal!";
_gameState = GameState.Message;
}
else
{
_messageToDisplay = "GOAL!";
score++;
_gameState = GameState.Message;
}
}
else
{
_messageToDisplay = "You missed the goal.";
_gameState = GameState.Message;
}
}
else if(_gameState == GameState.Message)
{
if(Mouse.GetState().RightButton == ButtonState.Pressed) // right click to continue playing
_gameState = GameState.Playing;
//you should also reset your ball position here
}
}
This way, whenever ball enters the goal area, it will either be a score, miss or hit on the goalkeeper. The game will then instantly change state so that those conditions aren't checked again until you right click with your mouse.
You could also put your input detection logic and ball and goalie position update logic inside these if's (you might not want for the player to be able to shoot another ball while the message is being displayed).

Cannot get laser to fire in 2D space invaders like game

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.
Your timer handler simply decrements fireTimer until it's zero. What instigates a re-rendering of the laser? Something needs to invoke laserFire to re-render the laser. Perhaps you meant to call laserFire from bulletTimer_Tick?

Categories

Resources