0
\$\begingroup\$

I'm new to coding. I'm trying to make a simple game where you can left click to spawn a salt "molecule" and right click to spawn a water one where the mouse cursor is. I don't know how to spawn a molecule where the mouse cursor is. I've been trying for a couple of days now.

//I've tried this:
Texture textureSalt;
textureSalt.loadFromFile("graphics/salt.png");
Sprite spriteSalt;
spriteSalt.setTexture(textureSalt);
spriteSalt.setPosition(/*I don't know what to put here; how to get it to spawn where the mouse is.*/)

Please help and thanks!

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

You can use the getPosition() function inside the Mouse class to retrieve the current position of the mouse cursor.

const sf::Vector2i mousePosition = sf::Mouse::getPosition();

// Convert the Vector2i, containing the mouse position, to a Vector2f since the setPosition function doesn't accept Vector2i
spriteSalt.setPosition(sf::Vector2f((float)mousePosition.x, (float)mousePosition.y));
\$\endgroup\$
3
  • \$\begingroup\$ When I do that, it gives me an error. I think it's because the getPosition function doesn't qualify as a parameter for setPosition, because it accepts only two floats. Is there any way I can express the getPosition as two floats? The error is "no instance of overloaded function sf::Sprite::setPosition matches the argument list" \$\endgroup\$ Commented Mar 8, 2022 at 16:32
  • \$\begingroup\$ @ElijahCampbell Yeah, I realized now that the setPosition function in the Sprite class only accepts either a sf::Vector2f or two floats, and not sf::Vector2i (which the getPosition function in the Mouse class returns). I've edited my answer to reflect that. \$\endgroup\$ Commented Mar 8, 2022 at 16:42
  • \$\begingroup\$ That seems to have worked. I don't have an error anymore. Thank you! \$\endgroup\$ Commented Mar 8, 2022 at 17:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .