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

Author Topic: mouse collision  (Read 1328 times)

0 Members and 1 Guest are viewing this topic.

michael

  • Guest
mouse collision
« 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);

            }
         }
      }

eXpl0it3r

  • SFML Team
  • Hero Member
  • *****
  • Posts: 11030
    • View Profile
    • development blog
    • Email
Re: mouse collision
« Reply #1 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. :)
Official FAQ: https://www.sfml-dev.org/faq.php
Official Discord Server: https://discord.gg/nr4X7Fh
——————————————————————
Dev Blog: https://duerrenberger.dev/blog/

 

anything