如何翻转图像并同时用枪指着鼠标? (SFML)
How do I flip an image and point a gun at the mouse at the same time? (SFML)
我正在制作一个玩家可以向鼠标射击的射击游戏,所以我让枪指向鼠标,但我不知道如何在向左转后正确翻转图像。我的意思是,我确实翻转了图像,但它没有正确对齐。我不太确定如何解释它,这是我的代码。
void PortalGun::update(Vector2i mPos) {
float pi = 3.14159265359;
float rotation = atan2(sprite.getGlobalBounds().top - mPos.y,sprite.getGlobalBounds().left - mPos.x) * 180 / pi;
int x = player->sprite.getGlobalBounds().left + 16;
int y = player->sprite.getGlobalBounds().top;
if (rotation > -90 && rotation < 90) {
player->dir = -1;
sprite.setTextureRect(IntRect(0, 32, 64, -32));
} else {
player->dir = 1;
sprite.setTextureRect(IntRect(0, 0, 64, 32));
}
sprite.setPosition(x, y + 15);
sprite.setRotation(rotation + 170);
}
当鼠标在枪的左侧时,它翻转图像但保持向上旋转,因此鼠标高出 20 个像素。我不能在旋转时只改变位置,那我该怎么办?抱歉听起来有点神秘,有点难以解释。
首先,您应该将精灵的原点设置为您想要旋转枪的点(通常是手柄或安装点)。为此,请使用 sf::Sprite::setOrigin()
。传递的坐标是相对于精灵左上角的。
要获取或设置精灵在世界中的位置(原点所在的位置),您可以使用 sf::Sprite::getPosition()
和 sf::Sprite::setPosition()
.
您的旋转可以保持原样。它将围绕您设置的原点旋转。
要镜像您的精灵,只需使用负因子缩放 (sf::Sprite::setScale()
) 它:sprite.setScale(-1, 1);
负因子将 mirror/flip 设置原点处的图像, 而不会强制您更新纹理坐标。
我正在制作一个玩家可以向鼠标射击的射击游戏,所以我让枪指向鼠标,但我不知道如何在向左转后正确翻转图像。我的意思是,我确实翻转了图像,但它没有正确对齐。我不太确定如何解释它,这是我的代码。
void PortalGun::update(Vector2i mPos) {
float pi = 3.14159265359;
float rotation = atan2(sprite.getGlobalBounds().top - mPos.y,sprite.getGlobalBounds().left - mPos.x) * 180 / pi;
int x = player->sprite.getGlobalBounds().left + 16;
int y = player->sprite.getGlobalBounds().top;
if (rotation > -90 && rotation < 90) {
player->dir = -1;
sprite.setTextureRect(IntRect(0, 32, 64, -32));
} else {
player->dir = 1;
sprite.setTextureRect(IntRect(0, 0, 64, 32));
}
sprite.setPosition(x, y + 15);
sprite.setRotation(rotation + 170);
}
当鼠标在枪的左侧时,它翻转图像但保持向上旋转,因此鼠标高出 20 个像素。我不能在旋转时只改变位置,那我该怎么办?抱歉听起来有点神秘,有点难以解释。
首先,您应该将精灵的原点设置为您想要旋转枪的点(通常是手柄或安装点)。为此,请使用
sf::Sprite::setOrigin()
。传递的坐标是相对于精灵左上角的。要获取或设置精灵在世界中的位置(原点所在的位置),您可以使用
sf::Sprite::getPosition()
和sf::Sprite::setPosition()
.您的旋转可以保持原样。它将围绕您设置的原点旋转。
要镜像您的精灵,只需使用负因子缩放 (
sf::Sprite::setScale()
) 它:sprite.setScale(-1, 1);
负因子将 mirror/flip 设置原点处的图像, 而不会强制您更新纹理坐标。