Character walks slow in my C# game - c#

The issue is I can't figure out why my character moves slow when I draw an image. All the timers are set to 1 interval and never changed. Any help would be greatly appreciated. Here is the entire project:
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 Rice_Boy_Tester_2
{
public partial class Form1 : Form
{
bool iggy = false;
bool left2 = false;
bool right2 = false;
bool Up2 = false;
bool Down2 = false;
bool Check2 = false;
bool left = false;
bool right = false;
bool Up = false;
bool Down = false;
bool Check = false;
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
// Empty block
}
private void Refresh_Tick(object sender, EventArgs e) {
this.Refresh();
}
private void PriceBoyWalk_Tick(object sender, EventArgs e) {
if (left) // Goes Left
Player.Left -= 1;
if (Player.Left < 170 & Check == false) {
// Checks how far away player is from form
left = false;
Up = true;
}
if (Up & Player.Left < 170) { // Goes Up
Player.Top -= 1;
Check = true;
}
if (Player.Top < 100 & Check) {
Up = false;
Down = true;
}
if (right) // Goes Right
Player.Left += 1;
if (Down) // Goes Down
Player.Top += 1;
if (Player.Top + 150 > this.ClientSize.Height) {
Check = false;
Down = false;
right = true;
}
if (Player.Left + 150 > this.ClientSize.Width)
right = false;
}
private void B1_Click(object sender, EventArgs e) {
this.Paint += new PaintEventHandler(form1_Pad1_Rice);
RiceBoyWalkGif.Enabled = true;
left = true;
left2 = true;
RiceBoyWalk.Enabled = true;
}
private void timer1_Tick(object sender, EventArgs e) {
if (left2) {
Player.Image = Image.FromFile("Rice-Boy-Walking-Left-Bouncing.gif"); // Animates RiceBoyWalkingLeft
left2 = false;
}
if (Player.Left < 170 & Check2 == false) {
// Checks how far away the player is from form
left2 = false;
Up2 = true;
}
if (Up2 & Player.Left < 170) { // Goes Up
this.Player.Size = new System.Drawing.Size(36, 76); // Changes size of the picture box to maintain quality
Player.Image = Image.FromFile("Rice-Boy-Walking-Up-Bouncing.gif"); // Animates RiceBoyWalkingUp
Check2 = true;
Up2 = false;
}
if (Player.Top < 101 & Check2) {
// Player.Top < 101 must be +1 greater than the RiceBoyWalkTimer
Up2 = false;
Down2 = true;
}
if (right2) {
this.Player.Size = new System.Drawing.Size(53, 77); // Changes size of the picture box to maintain quality
Player.Image = Image.FromFile("Rice-Boy-Walking-Right-Bouncing.gif"); // Animates RiceBoyWalkingRight
right2 = false;
}
if (Down2) { // Goes Down
Player.Image = Image.FromFile("Rice-Boy-Walking-Down.gif");
Down2 = false;
}
if (Player.Top + 150 > this.ClientSize.Height) {
iggy = true; // Shows that riceboy is approaching the starting point
Check2 = false;
Down2 = false;
right2 = true;
}
if (Player.Left + 150 > this.ClientSize.Width & iggy) {
right2 = false;
Player.Image = Properties.Resources.Rice_Boy_Standing_Left;
}
}
private void form1_Pad1_Rice(object sender, System.Windows.Forms.PaintEventArgs e) {
e.Graphics.DrawImage(Properties.Resources.Corn_Cobs, 120, 58, 50, 50);
// Draws Corn cobs Character goes slower when corn is drawing
// (x(-left), y(-Up), W, H)
}

Start with this:
Player.Image = Image.FromFile("Rice-Boy-Walking-Down.gif");
(and the other load routines).
On every tick? Seriously?
Load them once during initialization, store them in variables, reuse the images. Ever played a computer game? They are not trashing your disc trying to load all graphics asset every frame.
Disc access is slow. Image decoding is slow. And I doubt you change the images while the program runs.

Related

Holding down a key pauses the timer

I have an astro game with 2 picture boxes. One with a fireball(asteroid), and another with a UFO. I am moving the UFO with left and right key, handeled in keydown event. The asteroid falls from top to bottom. I am changing Y coordinate in a timer tick event. My problem is that if I hold down a key, the asteroid stops from falling and starts again as soon as I release the key.
UFOpictureBox is 100,100 picture box
Form Class
public partial class Form1 : Form
{
int hearts = 3, score = 0;
Point pozitieUFO, pozitieAsteroid;
Asteroid asteroid = new Asteroid();
Random random = new Random();
public Form1()
{
InitializeComponent();
DoubleBuffered = true;
KeyPreview = true;
pozitieUFO = UFOpictureBox.Location;
}
private void startBtn_Click(object sender, EventArgs e)
{
hearts = 3;
score = 0;
gameOverLabel.Visible = false;
startBtn.Visible = false;
exitBtn.Visible = false;
Controls.Add(asteroid);
pozitieAsteroid = asteroid.Location;
asteroidTimer.Start();
}
private void exitBtn_Click(object sender, EventArgs e)
{
this.Close();
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Left) pozitieUFO.X -= 10;
if (pozitieUFO.X <= 12) pozitieUFO.X = 12;
if (e.KeyData == Keys.Right) pozitieUFO.X += 10;
if (pozitieUFO.X >= 792) pozitieUFO.X = 792;
UFOpictureBox.Invalidate();
UFOpictureBox.Location = pozitieUFO;
}
private void asteroidTimer_Tick(object sender, EventArgs e)
{
pozitieAsteroid.Y += score/5 + 5;
if (pozitieAsteroid.Y > 420)
{
hearts--;
heartsLabel.Text = "Hearts: " + hearts;
if (hearts <= 0)
{
gameOver();
return;
}
pozitieAsteroid.Y = 1;
pozitieAsteroid.X = random.Next(12, 792);
}
if (asteroid.Bounds.IntersectsWith(UFOpictureBox.Bounds))
{
pozitieAsteroid.Y = 1;
pozitieAsteroid.X = random.Next(12, 792);
score++;
scoreLabel.Text = "Score: " + score;
}
asteroid.Invalidate();
asteroid.Location = pozitieAsteroid;
}
private void gameOver()
{
startBtn.Visible = true;
exitBtn.Visible = true;
gameOverLabel.Visible = true;
asteroidTimer.Stop();
}
}
Asteroid Class
class Asteroid : PictureBox
{
Random random = new Random();
public Asteroid()
{
Width = Height = 50;
SizeMode = PictureBoxSizeMode.StretchImage;
BackColor = Color.Transparent;
Image = Properties.Resources.fire;
Left = random.Next(12,792);
Top = 0;
}
}

Using/adding delegation method and BackgroundWorker to my currently fully working program

I've searched many topics but I can't seem to understand how to replace my existing methods with delegation+timer as I am currently using timer only. Also when adding BackgroundWorker to work with btng that moves the elevator down and opens the doors I get a multi-thread usage error stating that another thread is trying to insertdata in the .accdb where the main thread is recorded. I am adding the code which is not very long but fully working. Could someone give me a hint how to replace my existing methods with delegation and add one or two BackgroundWorkers to help the buttons that move the elevator and still keep the timers, please.
P.S. Do I need to share/change the database connection code in order to make it work with the backgroundworker? I'll add it if necessary. It's another couple of more lines..
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.Speech;
using System.Speech.Synthesis;
using System.Data.OleDb;
namespace rewrite
{
public partial class Form1 : Form
{
//variables
int y_up = 63;
int y_down = 376;
int x_door_left_close = 74;
int x_door_left_open = 12;
int x_door_right_close = 139;
int x_door_right_open = 200;
bool go_up = false;
bool go_down = false;
bool arrived_G = false;
bool arrived_1 = false;
//object
SpeechSynthesizer reader = new SpeechSynthesizer();
public Form1()
{
InitializeComponent();
}
private void timerliftdown_Tick(object sender, EventArgs e)
{
if (picturelift.Top <= y_down)
{
picturelift.Top += 1;
}
else
{
timerliftdown.Enabled = false;
btnup.Enabled = true;
btn1.Enabled = true;
btnclose.Enabled = true;
btnopen.Enabled = true;
btndown.BackColor = Color.Red;
btng.BackColor = Color.Red;
dooropendown();
arrived_G = true;
picturelift.Image = global::rewrite.Properties.Resources.Inside_of_the_lift;
displaypanel.Image = global::rewrite.Properties.Resources.G;
displaytop.Image = global::rewrite.Properties.Resources.G;
displaybottom.Image = global::rewrite.Properties.Resources.G;
}
}
private void timerliftup_Tick(object sender, EventArgs e)
{
if (picturelift.Top >= y_up)
{
picturelift.Top -= 1;
}
else
{
timerliftup.Enabled = false;
btndown.Enabled = true;
btng.Enabled = true;
btnclose.Enabled = true;
btnopen.Enabled = true;
btnup.BackColor = Color.Red;
btn1.BackColor = Color.Red;
dooropenup();
arrived_1 = true;
picturelift.Image = global::rewrite.Properties.Resources.Inside_of_the_lift;
displaypanel.Image = global::rewrite.Properties.Resources._1;
displaytop.Image = global::rewrite.Properties.Resources._1;
displaybottom.Image = global::rewrite.Properties.Resources._1;
}
}
private void dooropendown_Tick(object sender, EventArgs e)
{
if (doorleftdown.Left >= x_door_left_open && doorrightdown.Left <= x_door_right_open)
{
doorleftdown.Left -= 1;
doorrightdown.Left += 1;
}
else
{
timerdooropendown.Enabled = false;
}
}
private void timerdoorclosedown_Tick(object sender, EventArgs e)
{
if (doorleftdown.Left <= x_door_left_close && doorrightdown.Left >= x_door_right_close)
{
doorleftdown.Left += 1;
doorrightdown.Left -= 1;
}
else
{
timerdoorclosedown.Enabled = false;
if (go_up == true)
{
picturelift.Image = global::rewrite.Properties.Resources.lift_transparent;
displaypanel.Image = global::rewrite.Properties.Resources.up;
displaytop.Image = global::rewrite.Properties.Resources.up;
displaybottom.Image = global::rewrite.Properties.Resources.up;
reader.Speak("Going up");
timerliftup.Enabled = true;
go_up = false;
}
}
}
private void dooropenup_Tick(object sender, EventArgs e)
{
if (doorleftup.Left >= x_door_left_open && doorrightup.Left <= x_door_right_open)
{
doorleftup.Left -= 1;
doorrightup.Left += 1;
}
else
{
timerdooropenup.Enabled = false;
}
}
private void timerdoorcloseup_Tick(object sender, EventArgs e)
{
if (doorleftup.Left <= x_door_left_close && doorrightup.Left >= x_door_right_close)
{
doorleftup.Left += 1;
doorrightup.Left -= 1;
}
else
{
timerdoorcloseup.Enabled = false;
if (go_down == true)
{
picturelift.Image = global::rewrite.Properties.Resources.lift_transparent;
displaypanel.Image = global::rewrite.Properties.Resources.down;
displaytop.Image = global::rewrite.Properties.Resources.down;
displaybottom.Image = global::rewrite.Properties.Resources.down;
reader.Speak("Going down");
timerliftdown.Enabled = true;
go_down = false;
}
}
}
private void doorclosedown()
{
reader.Speak("doors closing");
insertdata("door closing #Ground floor");
timerdoorclosedown.Enabled = true;
timerdooropenup.Enabled = false;
}
private void dooropendown()
{
reader.Speak("Ground floor, doors opening");
insertdata("doors opening #Ground floor");
timerdoorclosedown.Enabled = false;
timerdooropendown.Enabled = true;
}
private void doorcloseup()
{
reader.Speak("doors closing");
insertdata("Doors closing #First Floor");
timerdoorcloseup.Enabled = true;
timerdooropenup.Enabled = false;
}
private void dooropenup()
{
reader.Speak("First Floor, doors opening");
insertdata("Doors Opening #First Floor");
timerdoorcloseup.Enabled = false;
timerdooropenup.Enabled = true;
}
private void going_up()
{
go_up = true;
doorclosedown();
btng.Enabled = false;
btndown.Enabled = false;
btnclose.Enabled = false;
btnopen.Enabled = false;
arrived_G = false;
insertdata("Lift going up");
}
private void going_down()
{
go_down = true;
doorcloseup();
btn1.Enabled = false;
btnup.Enabled = false;
btnclose.Enabled = false;
btnopen.Enabled = false;
arrived_1 = false;
insertdata("Lift going down");
}
private void btndown_Click(object sender, EventArgs e)
{
btnup.BackColor = Color.DarkCyan;
going_up();
}
private void btnup_Click(object sender, EventArgs e)
{
btndown.BackColor = Color.DarkCyan;
going_down();
}
private void btn1_Click(object sender, EventArgs e)
{
btn1.BackColor = Color.DarkCyan;
going_up();
}
private void btng_Click(object sender, EventArgs e)
{
btng.BackColor = Color.DarkOrange;
going_down();
}
private void btnclose_Click(object sender, EventArgs e)
{
if (arrived_G == true)
{
doorclosedown();
}
else if (arrived_1 == true)
{
doorcloseup();
}
}
private void btnopen_Click(object sender, EventArgs e)
{
if (arrived_G == true)
{
dooropendown();
}
else if (arrived_1 == true)
{
dooropenup();
}
}
private void btnalarm_Click(object sender, EventArgs e)
{
btnalarm.BackColor = Color.Green;
reader.Speak("Emergency Stop. Please exit carefully.");
insertdata("Emergency Stop!");
timerliftdown.Enabled = false;
timerliftup.Enabled = false;
timerdooropendown.Enabled = true;
timerdooropenup.Enabled = true;
displaypanel.Image = global::rewrite.Properties.Resources.alarmbellbutton;
displaytop.Image = global::rewrite.Properties.Resources.alarmbellbutton;
displaybottom.Image = global::rewrite.Properties.Resources.alarmbellbutton;
}

Zedgraph Serial plotting, cant pause the time variable. Environment.tickcount improper use

So here's my problem, First image
the highlighted portion was the time when i put the serial port close(i call it pause). Here's my code on that button:
private void disconnectbutton_Click(object sender, EventArgs e)
{
if (serialPort.IsOpen == false) return;
serialPort.Close();
}
Now, my problem here is, when I reconnect my Program to Arduino, here's my code:
public void connectbutton_Click(object sender, EventArgs e)
{
try
{
serialPort.PortName = portscombobox.Text;
serialPort.BaudRate = Convert.ToInt32(baudratecombobox.Text);
if (serialPort.IsOpen) return;
serialPort.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
MessageBox.Show("Invalid COM Port number... Please choose the correct COM Port number. \n Looking at Device manager will help :)");
Application.Restart();
}
The graph didn't follow the last points position, specifically the time it stopped. The curve pick the last y-value and draw it until the time I reconnect but there's no problem on the curve when disconnected/pause. You can look at the 2nd pic to show there's no feed while disconnected.
Second image
When i reconnect, the graph will look like the first picture above..
I believe my problem here was the improper use of Environment.tickcount and I tried searching for the solution but unfortunately I cant solve this on my own based on my knowledge.
I want my graph will only move to its x axis(time) when I try to connect it to arduino and read the data, and my elapsed time should only run when Im only connected not disconnected.
Here's my code:
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.IO.Ports;
using ZedGraph;
namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
string datafromcom;
delegate void SetTextCallback(string text);
// Starting time in milliseconds
int tickStart = 0;
//double time = 0;
//int t;
public Form1()
{
InitializeComponent();
checkbox1.Enabled = false;
checkbox2.Enabled = false;
checkbox3.Enabled = false;
checkbox4.Enabled = false;
}
public void connectbutton_Click(object sender, EventArgs e)
{
try
{
serialPort.PortName = portscombobox.Text;
serialPort.BaudRate = Convert.ToInt32(baudratecombobox.Text);
if (serialPort.IsOpen) return;
serialPort.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
MessageBox.Show("Invalid COM Port number... Please choose the correct COM Port number. \n Looking at Device manager will help :)");
Application.Restart();
}
serialPort.DtrEnable = true;
serialPort.RtsEnable = true;
getbutton.Enabled = false;
checkbox1.Enabled = true;
checkbox2.Enabled = true;
checkbox3.Enabled = true;
checkbox4.Enabled = true;
exitbutton.Enabled = false;
connectbutton.Enabled = false;
disconnectbutton.Enabled = true;
portscombobox.Enabled = false;
baudratecombobox.Enabled = false;
}
private void disconnectbutton_Click(object sender, EventArgs e)
{
if (serialPort.IsOpen == false) return;
serialPort.Close();
//tickStart += new tickStart();
exitbutton.Enabled = true;
connectbutton.Enabled = true;
disconnectbutton.Enabled = false;
portscombobox.Enabled = true;
baudratecombobox.Enabled = true;
checkbox1.Enabled = false;
checkbox2.Enabled = false;
checkbox3.Enabled = false;
checkbox4.Enabled = false;
}
private void Form1_Load(object sender, EventArgs e)
{
//this.Size = Screen.PrimaryScreen.WorkingArea.Size;
GraphPane myPane = z1.GraphPane;
z1.IsShowHScrollBar = true;
z1.IsShowVScrollBar = true;
z1.IsEnableHZoom = true;
z1.IsEnableVZoom = true;
// Disable the AutoScrollRange option (because we have set the scroll range manually)
z1.IsAutoScrollRange = true;
// Synchronize the Axes
z1.IsSynchronizeYAxes = true;
z1.IsSynchronizeXAxes = true;
z1.GraphPane.IsBoundedRanges = true;
// Horizontal pan allowed
z1.IsEnableHPan = true;
z1.IsEnableVPan = true;
z1.IsShowPointValues = true;
//z1.PointValueFormat = "0.00";
z1.PointDateFormat = "d";
// Change the color of the title
myPane.Title.FontSpec.FontColor = Color.Black;
myPane.Title.Text = " ";
myPane.XAxis.Title.Text = "Time (Seconds)";
myPane.YAxis.Title.Text = "Sample Potential, Volts";
// Save 20000 points. At 50 ms sample rate, this is one minute
// The RollingPointPairList is an efficient storage class that always
// keeps a rolling set of point data without needing to shift any data values
RollingPointPairList list = new RollingPointPairList(20000);
// Initially, a curve is added with no data points (list is empty)
// Color is blue, and there will be no symbols
LineItem curve = myPane.AddCurve(null, list, Color.Black, SymbolType.None);
//Sample at 50ms intervals
//timer1.Interval = 100;
//timer1.Enabled = true;
//timer1.Start();
// Just manually control the X axis range so it scrolls continuously
// instead of discrete step-sized jumps
myPane.XAxis.Scale.Min = 0;
myPane.XAxis.Scale.Max = 10;
myPane.XAxis.Scale.MinorStep = .5;
myPane.XAxis.Scale.MajorStep = 1;
myPane.YAxis.Scale.Min = -10;
myPane.YAxis.Scale.Max = 10;
myPane.YAxis.Scale.MinorStep = .1;
myPane.YAxis.Scale.MajorStep = 1;
// Add gridlines to the plot, and make them gray
myPane.XAxis.MajorGrid.IsVisible = true;
myPane.YAxis.MajorGrid.IsVisible = true;
myPane.XAxis.MajorGrid.Color = Color.LightGray;
myPane.YAxis.MajorGrid.Color = Color.LightGray;
myPane.Fill.Color = System.Drawing.Color.DarkGray;
// Make both curves thicker
curve.Line.Width = 2F;
// Increase the symbol sizes, and fill them with solid white
curve.Symbol.Size = 8.0F;
curve.Symbol.Fill = new Fill(Color.White);
// Add a background gradient fill to the axis frame
myPane.Chart.Fill = new Fill(Color.White,
Color.FromArgb(255, 255, 255), -45F);
// Scale the axes
z1.AxisChange();
//z1.AxisChange();
z1.GraphPane.AxisChange();
// Save the beginning time for reference
tickStart = Environment.TickCount;
}
private void exitbutton_Click(object sender, EventArgs e)
{
Application.Exit();
}
public void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
while (serialPort.BytesToRead > 0)
{
datafromcom = serialPort.ReadLine();
if (datafromcom.Trim() != "")
{
float dtfm = float.Parse(datafromcom);
//richtextbox.Text = "dynamic";
if (z1.GraphPane.CurveList.Count <= 0)
return;
// Get the first CurveItem in the graph
LineItem curve = z1.GraphPane.CurveList[0] as LineItem;
if (curve == null)
return;
// Get the PointPairList
IPointListEdit list = curve.Points as IPointListEdit;
// If this is null, it means the reference at curve.Points does not
// support IPointListEdit, so we won't be able to modify it
if (list == null)
return;
double time = (Environment.TickCount - tickStart) / 1000.0;
//curve.AddPoint(time, iDAT);
list.Add(time, dtfm);
Scale xScale = z1.GraphPane.XAxis.Scale;
if (time > xScale.Max - xScale.MajorStep)
{
xScale.Max = time + xScale.MajorStep ;
xScale.Min = xScale.Max - 10.0;
}
z1.AxisChange();
z1.Invalidate();
this.BeginInvoke(new SetTextCallback(SetText), new object[] { datafromcom });
}
}
}
catch (Exception )
{
}
}
private void SetText(string text)
{
this.richtextbox.Text = text;
//richtextbox.AppendText(text);
richtextbox.ScrollToCaret();
}
public void timer1_Tick(object sender, EventArgs e)
{
}
private void resetbutton_Click(object sender, EventArgs e)
{
Application.Restart();
}
}
}

How can i stop my player from moving in a direction when a collision is made

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;
namespace Game1
{
public partial class Form1 : Form
{
Graphics g;
Rectangle Player;
Rectangle Enemy;
Boolean left;
Boolean right;
Boolean up;
Boolean down;
int Playerx, Playery, Playerw, Playerh;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Playerx = 0;
Playery = 0;
Playerw = 32;
Playerh = 32;
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
g = e.Graphics;
//Draw Player
Player = new Rectangle(Playerx, Playery, Playerw, Playerh);
g.FillRectangle(Brushes.Blue, Player);
//Draw Enemy
Enemy = new Rectangle(100, 100, 32, 32);
g.FillRectangle(Brushes.Red, Enemy);
if (Player.IntersectsWith(Enemy.Left))
{
left = false;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (left == true)
{
Playerx -= 5;
}
if (right == true)
{
Playerx += 5;
}
if (up == true)
{
Playery -= 5;
}
if (down == true)
{
Playery += 5;
}
Invalidate();
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.A)
{
left = true;
right = false;
up = false;
down = false;
}
if (e.KeyCode == Keys.D)
{
right = true;
left = false;
up = false;
down = false;
}
if (e.KeyCode == Keys.W)
{
up = true;
down = false;
left = false;
right = false;
}
if (e.KeyCode == Keys.S)
{
down = true;
up = false;
left = false;
right = false;
}
}
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.A)
{
left = false;
}
if (e.KeyCode == Keys.D)
{
right = false;
}
if (e.KeyCode == Keys.W)
{
up = false;
}
if (e.KeyCode == Keys.S)
{
down = false;
}
}
}
}
I want to make the player stop moving when it touches the left side of the enemy but i keep getting an error, and it highlights
if (Player.IntersectsWith(Enemy.Left)) and says Can't convert int into System.Drawing.Rectangle any ideas?
I have tried to see if this works
if (Player.IntersectsWith(Enemy))
{
left = false;
right = false;
up = false;
down = false;
}
but of course it keeps the player in place.
You seem to want a specific collision.
You should try:
if(Player.X + Player.Width >= Enemy.X && Player.X < Enemy.X)
{
right = false;
}
This way you are checking if the right side of the player intersects the left side of the enemy and the left side of the players position is less than the left side of the enemy's position (the player is to the left of the enemy)
You will have to add in heights and stuff to that collision to make it so you can pass the enemy but I think for what you have posted it should work ok.
NOTE: Code is untested, let me know how you get on.

Keys do not work while using Keys.Down (Or up, left, right)

I am a beginner at C# (C Sharp) and I couldn't figure out why my Arrow keys would not work. Can anyone help me? Note: I am a beginner, I have been working at this for a while now and I can't figure it out. I have tried researching it with no luck, I hope I don't bother you. When I try and move it it doesn't work.
Here is my Form1
public partial class Form1 : Form
{
Graphics paper;
Snake snake = new Snake();
bool left = false;
bool right = false;
bool down = false;
bool up = false;
public Form1()
{
InitializeComponent();
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
paper = e.Graphics;
snake.drawSnake(paper);
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Down && up == false)
{
down = true;
up = false;
right = false;
left = false;
}
if (e.KeyData == Keys.Up && down == false)
{
down = false;
up = true;
right = false;
left = false;
}
if (e.KeyData == Keys.Right && left == false)
{
down = false;
up = false;
right = true;
left = false;
}
if (e.KeyData == Keys.Left && right == false)
{
down = false;
up = false;
right = false;
left = true;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (down) { snake.moveDown(); }
if (up) { snake.moveUp(); }
if (right) { snake.moveRight(); }
if (left) { snake.moveLeft(); }
this.Invalidate();
}
}
}
Here is my Snake class if you need it.
{
public Snake()
{
snakeRec = new Rectangle[3];
brush = new SolidBrush(Color.Blue);
x = 20;
y = 0;
width = 10;
height = 10;
for(int i = 0; i < snakeRec.Length; i++)
{
snakeRec[i] = new Rectangle(x, y, width, height);
x -= 10;
}
}
public void drawSnake(Graphics paper)
{
foreach (Rectangle rec in snakeRec)
{
paper.FillRectangle(brush, rec);
}
}
public void drawSnake()
{
for (int i = snakeRec.Length - 1; i > 0; i--)
{
snakeRec[i] = snakeRec[i - 1];
}
}
public void moveDown()
{
drawSnake();
snakeRec[0].Y += 10;
}
public void moveUp()
{
drawSnake();
snakeRec[0].Y -= 10;
}
public void moveRight()
{
drawSnake();
snakeRec[0].X += 10;
}
public void moveLeft()
{
drawSnake();
snakeRec[0].X -= 10;
}
}
}
I tried your code and it works well, so this is the only thing I can think of:
private void Form1_Load(object sender, EventArgs e)
{
timer1.Enabled = true;
}
Make sure that big guy is enabled.
Don't hold on to the Graphics from the Paint() event like that. Just pass e.Graphics directly to your Draw() method like this:
private void Form1_Paint(object sender, PaintEventArgs e)
{
snake.drawSnake(e.Graphics);
}
Also, make sure the Paint() event of the Form is wired up. Select the Form. Now click the "Lightning" Bolt" icon in the Properties Pane (bottom right by default). Find the Paint entry and change the dropdown to the right to "Form1_Paint".

Categories

Resources