SFML community forums

Help => General => Topic started by: michael on April 14, 2020, 03:05:03 am

Title: mouse collision
Post by: michael on April 14, 2020, 03:05:03 am
i need to know how to make mouse collision to sprites
to more than 2 sprites which is moving by the same button and here's the code
tell me how to do the mouse collision or what to do and what should i do to the code to upgrade it

   mp.x = sf::Mouse::getPosition(win).x;
         mp.y = sf::Mouse::getPosition(win).y;
         //b tcheck an el mouse gpwa el block fa bb3tlo 7dodo w makan el mouse
         if (isSpriteHover(bl1.getGlobalBounds(), sf::Vector2f(event.mouseButton.x, event.mouseButton.y)))
         {
            while (Mouse::isButtonPressed(Mouse::Left))
            {
               Vector2i pos = Mouse::getPosition(win);
               bl1.setPosition((float)pos.x, 50);

            }
         }

         if (isSpriteHover(bl2.getGlobalBounds(), sf::Vector2f(event.mouseButton.x, event.mouseButton.y)) == true)
         {
            while (Mouse::isButtonPressed(Mouse::Left))
            {
               Vector2i pos2 = Mouse::getPosition(win);
               bl2.setPosition((float)pos2.x, 250);

            }
         }if (isSpriteHover(bl3.getGlobalBounds(), sf::Vector2f(event.mouseButton.x, event.mouseButton.y)) == true)
         {
            while (Mouse::isButtonPressed(Mouse::Left))
            {
               Vector2i pos3 = Mouse::getPosition(win);
               bl3.setPosition(550,(float)pos3.y);

            }
         }
      }
Title: Re: mouse collision
Post by: eXpl0it3r on April 14, 2020, 04:42:13 pm
The sf::Rect<T> has a contains() function with which you can check whether a point is inside a rectangle, meaning you can check the mouse position with the global rect of the sprite.

Keep in mind to
a) get the relative mouse position by passing the window to the getPosition function and
b) to translate the mouse position to world coordinates with mapPixelToCoords on the window, so you can avoid the Vector2i to Vector2f casting and you'll never have to worry about if you use views

When positing code please use [code=cpp][/code] code tags. :)