I'm adding movable crates to my game and I need some help with my movement code. The way I've set up my movement code the crate's X and Y are moved according to a vector2 unless it hits a wall. Here's the movement code:
if (frameCount % (delay / 2) == 0)
{
for (int i = 0; i < Math.Abs(cSpeed.X); i++)
{
if (!Level.PlayerHit(new Rectangle(crateBounds.X + (Math.Sign(cSpeed.X) * 32), crateBounds.Y, crateBounds.Width, crateBounds.Height)))
{
if (!Level.CollideTiles(crateBounds.X + (Math.Sign(cSpeed.X) * 32), crateBounds.Y, crateBounds.Width, crateBounds.Height))
{
if (cSpeed.X != 0)
{
crateBounds.X += Math.Sign(cSpeed.X);
}
else
{
Equalize(2);
}
}
else
{
cSpeed.X = 0f;
}
}
else
{
if (!Level.CollideTiles(crateBounds.X - (Math.Sign(cSpeed.X) * 32), crateBounds.Y, crateBounds.Width, crateBounds.Height))
{
if (cSpeed.X != 0)
{
crateBounds.X -= Math.Sign(cSpeed.X);
}
else
{
Equalize(2);
}
}
else
{
cSpeed.X = 0f;
}
}
}
for (int i = 0; i < Math.Abs(cSpeed.Y); i++)
{
if (!Level.PlayerHit(new Rectangle(crateBounds.X, crateBounds.Y + Math.Sign(cSpeed.Y), crateBounds.Width, crateBounds.Height)))
{
if (!Level.CollideTiles(crateBounds.X, crateBounds.Y + Math.Sign(cSpeed.Y), crateBounds.Width, crateBounds.Height))
{
crateBounds.Y += Math.Sign(cSpeed.Y);
}
else
{
cSpeed.Y = 0f;
}
}
else
{
if (!Level.CollideTiles(crateBounds.X, crateBounds.Y - Math.Sign(cSpeed.Y), crateBounds.Width, crateBounds.Height))
{
crateBounds.Y -= Math.Sign(cSpeed.Y);
}
else
{
cSpeed.Y = 0f;
}
}
}
}
The frameCount and delay variables just slow down the movement somewhat. Anyway, I've added a tool to my game that acts as a gravity well (drawing objects into it's center; the closer they get to the center the faster they go) and what I'm trying to do is make it so that the crate will bounce off the player (and vice versa) when they collide. Thus far, my code only keeps the crate and player from getting stuck inside each other (the player can still get stuck under the crate, but I'll fix that later.) So what I'd like to know is how I can best make the crate bounce off the player.
The other movement problem I'm having is related to another tool which allows the player to pick up crates and move around with them. The problem is that the crate's movement while being carried isn't tied to the movement script (it moves the crate itself, instead of adding to speed), which makes the crate go through walls and such. I know what I have to do: make the crate's speed match the player's speed while the player is holding it, but I need the crate to snap to a certain position (just in front of the player) when the player grabs it and it needs to switch to another position (just in front of the player on the other side) when they player faces the other direction while holding it. What would be the best way to make it switch places while keeping all the movement tied to the speed vector?