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

Author Topic: [SOLVED] How can I make a rectangle follow the mouse cursor?  (Read 4957 times)

0 Members and 2 Guests are viewing this topic.

Blingu

  • Newbie
  • *
  • Posts: 15
    • View Profile
[SOLVED] How can I make a rectangle follow the mouse cursor?
« on: August 24, 2018, 06:55:14 pm »
Hi, I'm currently writing a simple game.
I want a rectangle to be at the cursor's position whenever the mouse has been moved. I found a solution on how to do it, but it's not working like it actually should. The rectangle is always located the same distance away, just like in the picture below (yellow dot imitates the cursor, it hasn't been caught on print screen):
(click to show/hide)

Code:
(click to show/hide)
I hope to receive some advice on how to do it, thanks in advance.
« Last Edit: September 17, 2018, 08:17:00 pm by Blingu »

eXpl0it3r

  • SFML Team
  • Hero Member
  • *****
  • Posts: 11034
    • View Profile
    • development blog
    • Email
Re: How can I make a rectangle follow the mouse cursor?
« Reply #1 on: August 24, 2018, 08:01:13 pm »
Check the documentation for sf:: Mouse::getPosition() it will show you an overload that takes the window.
Official FAQ: https://www.sfml-dev.org/faq.php
Official Discord Server: https://discord.gg/nr4X7Fh
——————————————————————
Dev Blog: https://duerrenberger.dev/blog/

Hapax

  • Hero Member
  • *****
  • Posts: 3379
  • My number of posts is shown in hexadecimal.
    • View Profile
    • Links
Re: How can I make a rectangle follow the mouse cursor?
« Reply #2 on: August 24, 2018, 08:09:04 pm »
It's likely that you want the mouse position within the window rather than global location.
Basically, add the window as a parameter to the mouse's getPosition() thus:
sf::Mouse::getPosition(*window);

This position, though, should be converted to the co-ordinate system. This is not really necessary if your view matches the window exactly but there's no reason to not convert just in case.

Assuming you access your window using a pointer called window, try something like:
const sf::Vector2i mousePosition{ sf::Mouse::getPosition(*window); };
const sf::Vector2f mouseCoord{ window->mapPixelToCoords(mousePosition) };
player.setPosition(mouseCoord);

See the view tutorial, especially the point about co-ordinate conversion:
https://www.sfml-dev.org/tutorials/2.5/graphics-view.php#coordinates-conversions



@eXpl0it3r, sorry but I'd already typed this out so posted it anyway ;)
Selba Ward -SFML drawables
Cheese Map -Drawable Layered Tile Map
Kairos -Timing Library
Grambol
 *Hapaxia Links*

Blingu

  • Newbie
  • *
  • Posts: 15
    • View Profile
Re: How can I make a rectangle follow the mouse cursor?
« Reply #3 on: August 29, 2018, 03:07:04 pm »
Thanks for your help, it can be closed and archived.