sfml enemy wall colliding in csharp

To detect collision between an enemy and a wall in SFML and C#, you can use the GlobalBounds property of the Sprite class to get the bounding rectangles of both the enemy and the wall, and then check if they intersect. Here's how:

main.cs
// first, get the bounding rectangles of the enemy and the wall
FloatRect enemyBounds = enemySprite.GetGlobalBounds();
FloatRect wallBounds = wallSprite.GetGlobalBounds();

// check if the enemy and the wall intersect
if (enemyBounds.Intersects(wallBounds))
{
    // if they do, move the enemy away from the wall along the x-axis
    if (enemyBounds.Left < wallBounds.Left)
    {
        enemySprite.Position = new Vector2f(wallBounds.Left - enemyBounds.Width, enemySprite.Position.Y);
    }
    else
    {
        enemySprite.Position = new Vector2f(wallBounds.Left + wallBounds.Width, enemySprite.Position.Y);
    }
}
620 chars
18 lines

This code assumes that the enemy and wall sprites are Sprite objects, and that they have been loaded and drawn to the SFML window. The GetGlobalBounds() method returns a FloatRect object that represents the bounding rectangle of the sprite in global (window) coordinates. The Intersects() method checks if two FloatRect objects intersect, and returns true if they do.

If the enemy collides with the wall, the code moves the enemy sprite along the x-axis to either the left or the right of the wall, depending on which side of the wall the enemy was on. You can adjust this code to fit your specific game's needs.

gistlibby LogSnag