I have been trying to make an online civil war RTS and then i came into a problem.
For about a week I've been trying to find a way to make a mechanism that makes the player follow the mouse when clicked. I've tried using 'for' loops and that was a mess, i even tried using one of the solutions from a another post back in 2013, i got an error.
here was the code i used,
sf::Vector2f totalMovement(sf::Mouse::getPosition(window).x) - battalion.getPosition().x, sf::Mouse::GetPosition(window).y - battalion.getPosition().y;
battalion.move(totalMovement * (1.f/30.f));
it would be a huge thanks if you could fix this code, or provide me new ones.
I've been using sfml for 3 weeks now so don't expect me to know everything yet.
Sincerely Stuff.
(i have the codeblocks version of sfml)
Here is a commented (untested) code with step by step explanations:
// on click event
{
auto clicked = window.convertPixelToCoords(sf::Mouse::getPosition(window)); // get clicked position converted to scene coordinates
auto direction = clicked - battalion.getPosition(); // compute direction to travel to reach the clicked point
direction = direction / std::sqrt(direction.x * direction.x + direction.y * direction.y); // normalize
}
// at every update
constexpr auto speed = 10.; // some constant, number of scene units to travel per second
car.move(direction * speed); // why 'car' while it was 'battalion' before??
// probably some check to see if entity has reached its destination, to stop moving
Don't hesitate to ask for more details :)
thank you for helping, but the line of code,
window.convertPixelToCoords
does not compile stating that the window (the main window) doesn't go with the .convertPixelToCoords line.