Old code
void Object::moveTo(Point _p) { // _p is always the center of the other object we want to go to
// adjust speed, don't worry it's not important here, I guess
if (current_speed == 0)
current_speed = speed/16;
else if (current_speed >= speed)
current_speed = speed;
else
current_speed *= 2;
// we want to calculate the new center of the
// our object (the one that run this method)
Point center;
// distance(x) calculate the distance between the center point of the object and
// the x point passed
if (distance(_p) <= current_speed) {
// we don't want shaking things!
center = Point(_p.x, _p.y);
} else {
// move diagonally
center.x = getCenter().x + current_speed*std::cos(angle(_p)); // angle calculates the angle between the center of the object and the _p point
center.y = getCenter().y + current_speed*std::sin(angle(_p));
}
// since we draw sprites by the top left corner we need to convert
// the center point to the correct top left point
center = toPosition(center);
sprite.setPosition(center);
}
New code
Notice that the origin of the sprite is set to be in the center so setPosition
will correctly set the center and that getCenter()
returns sprite.getPosition()
which is the center point.
void Object::moveTo(Point _p) {
Point center;
//std::cout << distance(_p) << std::endl;
if (distance(_p) <= speed) {
center = Point(_p.x, _p.y);
} else {
center.x = getCenter().x + speed*std::cos(angle(_p));
center.y = getCenter().y + speed*std::sin(angle(_p));
}
sprite.setPosition(center);
}