I was creating a little platforming game and i was stuck on the TOP and BOTTOM object collision for a block.
For some reason, the player would not stop falling when it overlapped the block. it would just reset jump to false and put force to 0, but not keep the player on top of the block.
Here is the code which i have done so far...
public partial class Form1 : Form
{
bool right;
bool left;
bool jump;
bool jumped;
int G = 20;
int force;
bool nothing;
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
label1.Text = "Bottom: " + player.Bottom + " Top: " + player.Top + " Left: " + player.Left + " Right: " + player.Right;
//Object Side Collision
if (player.Right > block.Left && player.Left < block.Right - player.Width / 2 && player.Bottom > block.Top && player.Top < block.Bottom)
{
right = false;
}
if (player.Left < block.Right && player.Right > block.Left + player.Width / 2 && player.Bottom > block.Top && player.Top < block.Bottom)
{
left = false;
}
//Jumping and Gravity
if (right == true)
player.Left += 4;
if (left == true)
player.Left -= 4;
if (jump == true)
player.Top -= force; force -= 1;
if (player.Top + player.Height >= screen.Height)
{
player.Top = screen.Height - player.Height;
jump = false;
}
else
{
player.Top += 5;
jumped = false;
nothing = false;
}
//Top and Bottom Object Collision
if (player.Left + player.Width - 1 > block.Left && player.Left + player.Width + 5 < block.Left + block.Width + player.Width && player.Top + player.Height >= block.Top && player.Top < block.Top)
{
player.Top = screen.Height - block.Height - player.Height;
force = 0;
jump = false;
}
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Right)
right = true;
if (e.KeyCode == Keys.Left)
left = true;
if (e.KeyCode == Keys.Escape)
this.Close();
if (jump != true)
if (e.KeyCode == Keys.Up)
{
if (jumped == true)
{ nothing = true; }
else
{if (player.Left + player.Width - 1 > block.Left && player.Left + player.Width + 5 < block.Left + block.Width + player.Width && player.Top + player.Height >= block.Top && player.Top < block.Top)
jumped = true;
jump = true; force = G;}
}
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Right)
right = false;
if (e.KeyCode == Keys.Left)
left = false;
}
private void screen_Paint(object sender, PaintEventArgs e)
{
}
}
I have tried to figure out the reason why it would not make the player stop when it hit the top of the block for about an hour (trying different code) and nothing i have tried work.
(trying different code)- why not use the debugger and find out why versus trial and error?