SFML community forums

Help => Graphics => Topic started by: luacher on March 08, 2025, 01:05:18 pm

Title: The problem with the rectangleshape size
Post by: luacher on March 08, 2025, 01:05:18 pm
I created a RectangleShape and applied a texture to it. However, since the size of the RectangleShape is larger than the texture, the hitbox is not accurate. How can I make their sizes equal?

Here's the code:
Player::Player(float movementSpeed) :
    playerCollider(body)
{
    SetTextures();
    stateTextures[PlayerState::Idle] = &idleTexture;
    stateTextures[PlayerState::Walk] = &walkTexture;

    keyMappings = {
        {sf::Keyboard::Key::A, {-1.f, 0.f}},
        {sf::Keyboard::Key::D, {1.f, 0.f}},
        {sf::Keyboard::Key::W, {0.f, -1.f}},
        {sf::Keyboard::Key::S, {0.f, 1.f}}
    };

    playerState = PlayerState::Idle;
    currentTexture = *stateTextures[playerState];
    playerAnimation.SetTexture(&currentTexture, 10, 0.2f);

    this->movementSpeed = movementSpeed;
    faceRight = true;

    body.setSize({ 80.f, 160.f });
    body.setOrigin(body.getSize().x / 2, body.getSize().y / 2);
    body.setPosition({ 0.f, 0.f });
    body.setTexture(&currentTexture);

    body.setOutlineColor(sf::Color::Red);
    body.setOutlineThickness(2.f);

    previousState = PlayerState::Idle;
}



void Player::Update(float deltaTime)
{
#pragma region movement
    sf::Vector2f movement(0.f, 0.f);
    for (const auto& key : keyMappings) {
        if (sf::Keyboard::isKeyPressed(key.key)) {
            movement += key.direction;

            if (movement.x > 0.f)
                faceRight = true;
            else
                faceRight = false;
        }
    }


    float magnitude = std::sqrt(movement.x * movement.x + movement.y * movement.y);
    if (magnitude != 0.f) {
        movement /= magnitude;
        movement *= movementSpeed * deltaTime;
        body.move(movement);
        playerState = PlayerState::Walk;
    }
    else {
        playerState = PlayerState::Idle;
    }

    if (playerState != previousState) {
        currentTexture = *stateTextures[playerState];
        body.setTexture(&currentTexture);
        playerAnimation.SetTexture(stateTextures[playerState], 10, 0.1f);
        previousState = playerState;
    }

    playerAnimation.Update(deltaTime, faceRight);
    body.setTextureRect(playerAnimation.animRect);
#pragma endregion
}
Title: Re: The problem with the rectangleshape size
Post by: G. on March 08, 2025, 04:50:02 pm
If your collision rectangle is different from your visual rectangle, then use a different rectangle (sf::FloatRect) for the collision and move it accordingly to the position of your RectangleShape
Title: Re: The problem with the rectangleshape size
Post by: Tigre Pablito on March 11, 2025, 02:55:08 am
Hello

If you want the RectangleShape size equal to the Texture's one, you can get the Texture size and apply it to the RectangleShape.