I'm working on getting a platformer prototype up and running in C# using monogame. The movement and collision "work" but are very awkward. For example, if you stand on the edge of a platform and jump straight up, you fall right through the platform. I'll post my code and hopefully someone sees something that doesn't look right. If any additional information is needed I can add more.
public Player(GraphicsDevice device)
{
x = 100;
y = 100;
width = 32;
height = 64;
maxVX = 10;
gravity = -2;
grounded = false;
Rect = new Rectangle(x, y, width, height);
WhiteRectangle = new Texture2D(device, 1, 1);
WhiteRectangle.SetData(new[] { Color.White });
}
public void Update()
{
rect = new Rectangle(x, y, width, height);
if (!grounded || standingOn==null)
{
aY = gravity;
}else
{
aY = 0;
}
VY += AY;
VX += AX;
if (aX > 10) aX = 10;
if (aX < -10) aX = -10;
if (vX > maxVX) vX = maxVX;
if (vX < -maxVX) vX = -maxVX;
System.Console.WriteLine(vX +":" + aX);
lastX = x;
lastY = y;
x += VX;
y -= VY;
}
public void CollisionCheck(List<Platform> collideables)
{
foreach(var p in collideables)
{
if (rect.Intersects(p.Rect))
{
Rectangle intersection = Rectangle.Intersect(rect, p.Rect);
if(intersection.Height < intersection.Width)
{
if (y < p.Y)
{
standingOn = p;
grounded = true;
y = p.Y - height;
vY = 0;
aY = 0;
}else
{
y = p.Y + p.Height + 1;
vY = 0;
}
}else
{
if(x < p.X)
{
x = p.X - width - 1;
}else
{
x = p.X + p.Width + 1;
}
}
vX = 0;
aX = 0;
}
}
//Check if player falls off platform
if (standingOn != null)
{
if(x+width < standingOn.X || x > standingOn.X +standingOn.Width)
{
grounded = false;
standingOn = null;
}
}
}
public void ApplyFriction()
{
aX = 0;
if (vX > 0)
aX -= 2;
if (vX < 0)
aX += 2;
}
EDIT: Almost forgot to include the code that changes the acceleration
player.AX += (int)(pad.ThumbSticks.Left.X * 10) / 5;