1
\$\begingroup\$

I have my camera follow my player and it works perfectly, I had some issues with collision and managed to get it working, but now my camera follows my player when it gets pushed back so the camera just flickers when holding down the button towards a collision since it's following the player! I tried to stop the camera from following the player on an axis when colliding with something but it still makes the character look weirdly bouncing from walls. This is my code:

Camera Updating

if (player.CameraFollow)
{
    Camera.IsFollowingObject = true;
    if (Camera.IsFollowingObject)
    {
        Vector2 relativePlayerpos = -player.CurrentPos;
        relativePlayerpos.X += Camera.Viewport.Height;
        relativePlayerpos.Y += Camera.Viewport.Width/2 - player.Sprite.SourceRect.Height/2;
        Camera.Pos = relativePlayerpos;
    }
}

Collision Handler

public void CollisionHandler(ref Player player, Rectangle tileRect)
{
    //push left
    int left = Math.Abs(tileRect.Left - player.CollisionBox.Right);
    //push top
    int top = Math.Abs(tileRect.Top - player.CollisionBox.Bottom);
    //push right
    int right = Math.Abs(tileRect.Right - player.CollisionBox.Left);
    //push bottom
    int bottom = Math.Abs(tileRect.Bottom - player.CollisionBox.Top);

    if (left < top && left < right && left < bottom)
    {
        player.Velocity.X = 0;
        player.Sprite.Position.X -= left;
    }
    else if (right < top && right < left && right < bottom)
    {
        player.Velocity.X = 0;
        player.Sprite.Position.X += right;
    }
    else if (top < left && top < right && top < bottom)
    {
        player.Velocity.Y = 0;
        player.Sprite.Position.Y -= top;
    }
    else if (bottom < left && bottom < right && bottom < top)
    {
        player.Velocity.Y = 0;
        player.Sprite.Position.Y += bottom;
    }
}

This is what the collision basically does:

2d topdown collision

Any help is appreciated, thank you!

\$\endgroup\$
  • \$\begingroup\$ Try handling the collision before rendering \$\endgroup\$ – Bálint Sep 26 '17 at 18:26
  • \$\begingroup\$ I handle the collision when the game updates each tile and I find a collidable tile, then I check if the player intersects with that, how would I handle the collision if the tiles haven't loaded? Or should I move my whole collision handling into the player's update? \$\endgroup\$ – Amirgem Sep 27 '17 at 4:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.