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

Author Topic: How to Convert Touch Sprite to world coordinates  (Read 2043 times)

0 Members and 1 Guest are viewing this topic.

Jan666

  • Jr. Member
  • **
  • Posts: 64
    • View Profile
How to Convert Touch Sprite to world coordinates
« on: May 13, 2022, 12:13:31 am »
Hi, i need Help, by the following problem:
I have a Sprite who present a touch Button. when i touch it, the color change. The problem is, that the full touch contact not on the Sprite is just next to it. I need to implement mapToPixelCoordinate to convert the Touch to world coordinates. Here is my code


int main(int argc, char *argv[])
{
        sf::RenderWindow window(sf::VideoMode::getDesktopMode(), "Hello SFML");

        sf::Sprite sprite;
        sf::Texture tex;
        sf::Texture tex2;
        tex.loadFromFile("red.png");
        tex2.loadFromFile("green.png");
        sprite.setPosition(300, 700);
                       
        while (window.isOpen())
        {

                sf::Event event;
                while (window.pollEvent(event));
               

                                                               
                sf::FloatRect frec = sprite.getGlobalBounds();
               
                               
if(frec.contains(sf::Touch::getPosition(0).x, sf::Touch::getPosition(0).y)){
                               
                        sprite.setTexture(tex);                
                }
                else
                {                      
                        sprite.setTexture(tex2);
                }
                               
                window.clear(sf::Color(0, 0, 0));      
                window.draw(sprite);
                window.display();
               
        }
        return 0;
}

 

Someone know how i do this? Maybe put this code insdie it? I
sf::Vector2i pixelPos = sf::Touch::getPosition(0, window);
sf::Vector2f worldPos = window.mapPixelToCoords(pixelPos);
 

dont know how to fix it in the right way

Jan666

  • Jr. Member
  • **
  • Posts: 64
    • View Profile
Re: How to Convert Touch Sprite to world coordinates
« Reply #1 on: May 13, 2022, 11:05:50 pm »
Here is the solution for all who stuck in the same mud:

sf::Vector2i pixelPos = sf::Touch::getPosition(0, window);
sf::Vector2f worldPos = window.mapPixelToCoords(pixelPos);

sf::FloatRect frec = sprite.getGlobalBounds();

       
        if(frec.contains(worldPos)){