So I'm using SFML 2. I'm making an RTS, and I'm working on the unit moving at the moment. Pretty straight forward: you click a position, the selected unit(s) move there. Simple, right?
So here's my code for the movement. It works for the most part.. But not really.
Basically, when your mouse is in the middle of your Y axis (768 / 2), it works. Perfectly. But when you slowly go up the y axis (- or +), the sprite gets A LOT faster. When you're around 0 / 768, you don't even see the sprite move. Which brings me to my final problem..
When the sprite gets there (normal speed or not), the sprite disappears from the screen! Being the clever guy I am (totally not a lie), I found these were the values of the sprite:
X = -2147483648
Y = -2147483648
Whaaaat! Makes no sense, right? Well, here's the code. You're welcome make fun of it all, just tell me another and better way.
Thank you a lot if you got through all of this text. You're a life saver!
Unit.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
void Unit::Move(sf::RenderWindow& Window)
{
static int targetX;
static int targetY;
static float angleX;
static float angleY;
static float distance;
static float directionX;
static float directionY;
static float velocityX;
static float velocityY;
positionX = sprite.getPosition().x;
positionY = sprite.getPosition().y;
if(selected == true && sf::Mouse::isButtonPressed(sf::Mouse::Right))
{
sprite.move(velocityX, velocityY);
}
targetX = sf::Mouse::getPosition(Window).x;
targetY = sf::Mouse::getPosition(Window).y;
angleX = sf::Mouse::getPosition(Window).x - sprite.getPosition().x;
angleY = sf::Mouse::getPosition(Window).y - sprite.getPosition().y;
distance = sqrt((angleX * angleX) + (angleY + angleY));
directionX = angleX / distance;
directionY = angleY / distance;
velocityX = directionX * speed;
velocityY = directionY * speed;
}
|