Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Getting a sprite to follow the camera  (Read 1464 times)

0 Members and 1 Guest are viewing this topic.

BreadMonika

  • Newbie
  • *
  • Posts: 5
    • View Profile
Getting a sprite to follow the camera
« on: March 14, 2023, 01:12:11 am »
Hi, SFML community, I'm having issues trying to get a sprite to be fixed to a certain screen position even when the camera is moving, pretty much what I need is having a sprite with a fixed position on the screen or rather a fixed position of the camera and make it remain in there even when the view is moving around. but I want to achieve this, without using another view. I know it would be better to have a view for the HUID but, its just one sprite in this case.

I attach a gif to the problem in question.

Here is my code without my tries, as you can see I have a bool in case a sprite is fixed.

void RenderSystem::update(std::shared_ptr<sf::RenderWindow> renderer, std::unique_ptr<Bread::AssetManager>& assetManager, sf::View & camera)
{
    for (size_t i(0);i<layers.size();i++)
    {
        for(auto &it: *(*layers[i].getEntities()).getEntities())
        {
            auto& transform(it.getComponent<TransformComponent>());
            auto& sprite(it.getComponent<SpriteComponent>());
            auto& cameraPos(camera.getCenter());
            auto& cameraSize(camera.getSize());

            sf::Vector2f cameraCorner(cameraPos.x - (cameraSize.x / 2), cameraPos.y - (cameraSize.y / 2));
            sf::FloatRect entityRect(transform.position.x, transform.position.y, transform.scale.x * sprite.width, transform.scale.y * sprite.height);

            if(!isInsideOfCamera(entityRect,camera) and !sprite.isFixed)
            {
                continue;
            }

            sf::IntRect srcRect = sprite.srcRect;
            sf::Vector2f destRect =
            {
                (transform.position.x),
                (transform.position.y)
            };

            sf::Sprite sprite2(*assetManager->getTexture(sprite.assetId),srcRect);
            sprite2.setPosition(destRect);
            sprite2.setScale(transform.scale.x,transform.scale.y);
            renderer->draw(sprite2);
        }
    }
   
}
 

Thanks in advance. Have a good day ^-^/

eXpl0it3r

  • SFML Team
  • Hero Member
  • *****
  • Posts: 11042
    • View Profile
    • development blog
    • Email
Re: Getting a sprite to follow the camera
« Reply #1 on: March 14, 2023, 11:07:53 pm »
I mean you already know the preferred solution, to use a separate view for the HUD ;D

If you don't want to do that, then you have to move the HUD elements with the map moving, similar to how your helicopter is actually "standing still" on the screen, once you start moving the camera.
Official FAQ: https://www.sfml-dev.org/faq.php
Official Discord Server: https://discord.gg/nr4X7Fh
——————————————————————
Dev Blog: https://duerrenberger.dev/blog/

 

anything