I want to make a program where a picturebox is moving inside of the panel. If a button up is pressed, then it moves only up, if the button down is pressed it moves only down etc. Then there are two buttons true and false, if true is pressed then the timer is working, if the button false is pressed then the timer isn't working.
The problem is that the program does do all of the above, but I can't go and press the button up, then left etc. It only works for one command at a time, and once one of them is pressed, it looks like all of the others aren't working(excluding true and false buttons, those always work).
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 WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
bool up = false;
bool down = false;
bool left = false;
bool right = false;
private void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
}
private void button2_Click(object sender, EventArgs e)
{
timer1.Enabled = false;
bool up = false;
bool down = false;
bool left = false;
bool right = false;
}
private void timer1_Tick(object sender, EventArgs e)
{
if(up){
down = false;
left = false;
right = false;
while (!(pictureBox1.Top==panel1.Top))
{
pictureBox1.Top -= 1;
}
}
else if (down)
{
up = false;
left = false;
right = false;
while (!(pictureBox1.Top+pictureBox1.Height == panel1.Top+panel1.Height-10))
{
pictureBox1.Top += 1;
}
}
else if (right)
{
up = false;
down = false;
left = false;
while (!(pictureBox1.Left + pictureBox1.Width == panel1.Left + panel1.Width-10))
{
pictureBox1.Left += 1;
}
}
else if (left)
{
up = false;
right = false;
down = false;
while (!(pictureBox1.Left == panel1.Left))
{
pictureBox1.Left -= 1;
}
}
}
private void button6_Click(object sender, EventArgs e)
{
up = true;
}
private void button5_Click(object sender, EventArgs e)
{
down = true;
}
private void button4_Click(object sender, EventArgs e)
{
left = true;
}
private void button3_Click(object sender, EventArgs e)
{
right = true;
}
I'm not sure where the problem is. Is it in the bool statements?
Related
I am doing a small project for fun where I'm making a local music application (kinda like Spotify), and I would like for the slider I use for the music track (MusicSlider) to snap to where I click my mouse. I know you can do this with isMoveToPointEnabled = true, but since I have a really messy timer_tick (Update) function and whatnot, I haven't found a way of making it work properly.
I have tried for so long, and nothing my small brain comes up with works.
The problem is: Whenever I click on the slider like I should do, It immediately just snaps back.
The code is really messy because of the fact i'm not good at making clean code, and that the code has undergone a lot of brainstorming, and I haven't taken the time to fix it up yet.
Anyways, here is the code:
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Music_Application.MVVM.View;
using System.Globalization;
using Music_Application.MVVM.ViewModel;
using Microsoft.Win32;
using System.Windows.Controls.Primitives;
using System.Windows.Media.Animation;
using System.Threading;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
namespace Music_Application
{
public partial class MainWindow : Window
{
bool songProgressDrag;
public bool fadeIn;
public bool fadeOut;
public double i;
StreamWriter? sw;
StreamReader? sr;
System.Windows.Threading.DispatcherTimer timer = new System.Windows.Threading.DispatcherTimer();
public MainWindow()
{
InitializeComponent();
VolumeSlider.Value = Read(VolumeSlider.Value, "./Data/VolumeSave.txt");
MusicPlayer.mediaPlayer.Open(new Uri("./Example Items/Music/NeverGonnaGiveYouUp.mp3", UriKind.RelativeOrAbsolute));
MusicSlider.AddHandler(MouseLeftButtonDownEvent, new MouseButtonEventHandler(WhenMovingMusicSlider), true);
MusicSlider.AddHandler(MouseLeftButtonUpEvent, new MouseButtonEventHandler(SyncMusicProgressToSlider), true);
timer.Interval = TimeSpan.FromSeconds(0.01);
timer.Tick += Update;
timer.Start();
}
private void SongProgress_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double>? e)
{
UpdateSongProgress();
}
private void ChooseSong(object sender, RoutedEventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "MP3 files (*.mp3)|*.mp3|All files (*.*)|*.*";
openFileDialog.Multiselect = false;
if (openFileDialog.ShowDialog() == true)
{
MusicPlayer.mediaPlayer.Open(new Uri(openFileDialog.FileName));
TagLib.File tagFile = TagLib.File.Create(openFileDialog.FileName);
TagLib.IPicture coverArt = tagFile.Tag.Pictures[0];
if(coverArt != null)
{
MemoryStream ms = new MemoryStream(coverArt.Data.Data);
ms.Seek(0, SeekOrigin.Begin);
BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.StreamSource = ms;
bitmap.EndInit();
SongCover.ImageSource = bitmap;
}
SongName.Text = tagFile.Tag.Title;
ArtistName.Text = tagFile.Tag.FirstAlbumArtist;
MusicPlayer.mediaPlayer.Open(new Uri(openFileDialog.FileName, UriKind.RelativeOrAbsolute));
if (MusicPlayer.isPlaying)
{
MusicPlayer.mediaPlayer.Play();
}
MusicSlider.Value = 0;
while(!MusicPlayer.mediaPlayer.NaturalDuration.HasTimeSpan)
{
}
}
}
bool nisse;
private void SyncMusicProgressToSlider(object sender, MouseButtonEventArgs e)
{
while(MusicPlayer.mediaPlayer.Position != TimeSpan.FromSeconds(MusicSlider.Value))
{
MusicPlayer.mediaPlayer.Position = TimeSpan.FromSeconds(MusicSlider.Value);
}
songProgressDrag = false;
}
private void WhenMovingMusicSlider(object sender, MouseButtonEventArgs e)
{
songProgressDrag = true;
}
void Update(object? sender, EventArgs e)
{
if (MusicPlayer.mediaPlayer.NaturalDuration.HasTimeSpan)
{
if (!songProgressDrag && MusicPlayer.isPlaying)
{
MusicSlider.Value = MathF.Round((float)MusicPlayer.mediaPlayer.Position.TotalSeconds);
}
if (MusicPlayer.repeat && MusicSlider.Value == MusicSlider.Maximum && !songProgressDrag)
{
MusicPlayer.mediaPlayer.Position -= MusicPlayer.mediaPlayer.Position;
MusicSlider.Value = 0;
}
if (!MusicPlayer.repeat && MusicSlider.Value == MusicSlider.Maximum && !songProgressDrag)
{
MusicPlayer.mediaPlayer.Position -= MusicPlayer.mediaPlayer.Position;
MusicSlider.Value = 0;
PlayButton.IsChecked = false;
}
}
PlayButton.IsChecked = MusicPlayer.isPlaying;
if (MusicPlayer.isPlaying)
{
PauseIcon.Visibility = Visibility.Visible;
PlayIcon.Visibility = Visibility.Hidden;
}
else
{
PauseIcon.Visibility = Visibility.Hidden;
PlayIcon.Visibility = Visibility.Visible;
}
if (fadeIn)
{
if (MusicPlayer.mediaPlayer.Volume < VolumeSlider.Value / 100)
{
i += VolumeSlider.Value / 100 / 12;
MusicPlayer.mediaPlayer.Volume = i;
}
else
{
MusicPlayer.mediaPlayer.Volume = VolumeSlider.Value / 100;
fadeIn = false;
}
}
if (fadeOut)
{
if (MusicPlayer.mediaPlayer.Volume > 0)
{
i -= VolumeSlider.Value / 100 / 12;
MusicPlayer.mediaPlayer.Volume = i;
}
else
{
MusicPlayer.mediaPlayer.Volume = 0;
MusicPlayer.Pause();
MusicSlider.Value = MathF.Round((float)MusicPlayer.mediaPlayer.Position.TotalSeconds);
fadeOut = false;
}
}
UpdateSongProgress();
}
private void UpdateSongProgress()
{
MusicSlider.Maximum = Convert.ToDouble(MathF.Round((float)MusicPlayer.mediaPlayer.NaturalDuration.TimeSpan.TotalSeconds));
TimeSpan length = TimeSpan.FromSeconds(MathF.Round((float)Convert.ToDouble(MusicPlayer.mediaPlayer.NaturalDuration.TimeSpan.TotalSeconds)));
TimeSpan progress = TimeSpan.FromSeconds(MusicSlider.Value);
string songLength = string.Format("{0:D2}:{1:D2}",
length.Minutes,
length.Seconds);
string songProgress = string.Format("{0:D2}:{1:D2}",
progress.Minutes,
progress.Seconds);
if (songLength.Length == 5 && songLength.StartsWith("0"))
{
SongValueTotal.Text = songLength.Remove(0, 1);
}
else if (songLength.Length == 5 && !songLength.StartsWith("0"))
{
SongValueTotal.Text = songLength;
}
else if (songLength.Length == 8 && songLength.StartsWith("0"))
{
SongValueTotal.Text = songLength.Remove(0, 1);
}
else if (songLength.Length == 8 && !songLength.StartsWith("0"))
{
SongValueTotal.Text = songLength;
}
if (songProgress.Length == 5 && songProgress.StartsWith("0"))
{
SongValueProgress.Text = songProgress.Remove(0, 1);
}
else if (songProgress.Length == 5 && !songProgress.StartsWith("0"))
{
SongValueProgress.Text = songProgress;
}
else if (songProgress.Length == 8 && songProgress.StartsWith("0"))
{
SongValueTotal.Text = songLength.Remove(0, 1);
}
else if (songProgress.Length == 8 && !songProgress.StartsWith("0"))
{
SongValueTotal.Text = songLength;
}
}
private void VolumeChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
MusicPlayer.mediaPlayer.Volume = VolumeSlider.Value / 100;
}
public void Pause(object sender, RoutedEventArgs e)
{
PauseIcon.Visibility = Visibility.Hidden;
PlayIcon.Visibility = Visibility.Visible;
MusicPlayer.isPlaying = false;
fadeOut = true;
fadeIn = false;
i = VolumeSlider.Value / 100;
}
public void Play(object sender, RoutedEventArgs e)
{
PauseIcon.Visibility = Visibility.Visible;
PlayIcon.Visibility = Visibility.Hidden;
if (MusicPlayer.mediaPlayer.NaturalDuration.HasTimeSpan)
{
MusicPlayer.Play();
}
MusicPlayer.isPlaying = true;
fadeIn = true;
fadeOut = false;
i = 0;
}
public void RepeatOn(object sender, RoutedEventArgs e)
{
RepeatButtonDot.Visibility = Visibility.Visible;
MusicPlayer.repeat = true;
}
public void RepeatOff(object sender, RoutedEventArgs e)
{
RepeatButtonDot.Visibility = Visibility.Hidden;
MusicPlayer.repeat = false;
}
protected override void OnClosed(EventArgs e)
{
Write(VolumeSlider.Value, "./Data/VolumeSave.txt");
base.OnClosed(e);
Application.Current.Shutdown();
}
private void Write(object sender, string url)
{
sw = new StreamWriter(url);
sw.WriteLine(sender.ToString());
sw.Close();
}
private double Read(object sender, string url)
{
sr = new StreamReader(url);
sender = Convert.ToDouble(sr.ReadLine());
sr.Close();
return (double)sender;
}
private void FillHomeButton(object sender, RoutedEventArgs e)
{
HomeButtonSelected.Visibility = Visibility.Visible;
HomeButtonUnselected.Visibility = Visibility.Hidden;
HomeButtonText.Foreground = System.Windows.Media.Brushes.White;
}
private void UnfillHomeButton(object sender, RoutedEventArgs e)
{
HomeButtonUnselected.Visibility = Visibility.Visible;
HomeButtonSelected.Visibility = Visibility.Hidden;
HomeButtonText.Foreground = new SolidColorBrush(System.Windows.Media.Color.FromRgb(70,70,70)); /*(Brush) new BrushConverter().ConvertFrom("#b3b3b3");*/
}
private void ExitPlaylistCustomizer(object sender, RoutedEventArgs e)
{
CustomizePlaylistPopup.Visibility = Visibility.Hidden;
}
}
public static partial class MusicPlayer
{
public static bool isPlaying;
public static bool repeat;
public static MediaPlayer mediaPlayer = new MediaPlayer();
public static void Play()
{
var mainWindow = (MainWindow)Application.Current.MainWindow;
if (mediaPlayer.NaturalDuration.HasTimeSpan)
{
mediaPlayer.Play();
}
isPlaying = true;
}
public static void Pause()
{
mediaPlayer.Pause();
isPlaying = false;
}
}
}
And also, here is my slider in xaml in case you need it:
<Slider IsManipulationEnabled="True" TickFrequency="1" x:Name="MusicSlider" ValueChanged="SongProgress_ValueChanged" IsSnapToTickEnabled="True" IsMoveToPointEnabled="True" Style="{StaticResource Horizontal_Slider}"
VerticalAlignment="Center" Margin="50,0,50,0"/>
The movement of slider thumb by clicking slider track seems not fire MouseLeftButtonDownEvent. As a result, you timer logic could revert slider's value before MouseLeftButtonUpEvent is fired.
I have no idea on direct solution for this issue. Perhaps it would be better to sync slider value and media player by ValueChanged event.
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;
}
I've been creating the game Simon in a windows form using C#. I'm having a problem in the labels that blink to show the pattern. When one label is required to blink twice (because it appears in the pattern twice) it will only blink once. Also, in general the labels will sometimes not blink in the correct order they are meant to (i.e the second in the pattern blinks before the first). Any assistance in how to fix this or in general how to improve on my code would be great. I have only been using C# for the last few weeks and it's part of a university project.
Have attached the code and a picture of what the windows form looks like.
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.Windows.Forms;
namespace Simon2
{
public partial class Form1 : Form
{
List<int> sequence = new List<int>();
Random rnd = new Random();
int number = 0;
public Form1()
{
InitializeComponent();
sequence.Add(rnd.Next(0, 4));
hey();
}
void hey()
{
foreach (int colour in sequence)
{
switch (colour)
{
case 0: {
timer1.Enabled = true;
break;
}
case 1: {
timer2.Enabled = true;
break;
}
case 2: {
timer3.Enabled = true;
break;
}
case 3: {
timer4.Enabled = true;
break;
}
}
}
}
void pattern(int colour)
{
if (sequence[number] == colour)
{
label1.Text = ("Score: " + sequence.Count);
sequence.Add(rnd.Next(0, 4));
number = 0;
hey();
}
else
{
MessageBox.Show("Fail!");
Application.Exit();
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (Red1.BackColor == Color.Transparent)
{
Red1.BackColor = Color.Red;
timer1.Interval = 300;
}
else
{
Red1.BackColor = Color.Transparent;
timer1.Interval = 300;
timer1.Stop();
}
}
private void timer2_Tick(object sender, EventArgs e)
{
if (Blue1.BackColor == Color.Transparent)
{
Blue1.BackColor = Color.Blue;
timer2.Interval = 300;
}
else
{
Blue1.BackColor = Color.Transparent;
timer2.Interval = 300;
timer2.Stop();
}
}
private void timer3_Tick(object sender, EventArgs e)
{
if (Yellow1.BackColor == Color.Transparent)
{
Yellow1.BackColor = Color.Yellow;
timer3.Interval = 300;
}
else
{
Yellow1.BackColor = Color.Transparent;
timer3.Interval = 300;
timer3.Stop();
}
}
private void timer4_Tick(object sender, EventArgs e)
{
if (Green1.BackColor == Color.Transparent)
{
Green1.BackColor = Color.Lime;
timer4.Interval = 300;
}
else
{
Green1.BackColor = Color.Transparent;
timer4.Interval = 300;
timer4.Stop();
}
}
private void Red_Click(object sender, EventArgs e)
{
pattern(0);
}
private void Blue_Click(object sender, EventArgs e)
{
pattern(1);
}
private void Yellow_Click(object sender, EventArgs e)
{
pattern(2);
}
private void Green_Click(object sender, EventArgs e)
{
pattern(3);
}
}
}
I am not familiar with the game itself, my understanding is that one light after the other has to light up.
My suggestion: Use Thread.sleep (UI will not be responsive while this does it's thing), instead of timers, directly in the switch:
switch (colour){
case 0: {
Red1.BackColor = Color.Red;
Thread.Sleep(500);
Red1.BackColor = Color.Transparent;
break;
}
edit:
a better way would be to use a while loop which checks if a certain amount of ms elapsed and put Application.DoEvents(); in there
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.
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.