嘿,所以我创建了一个“body”类,它继承自 SFML 中的 sf::drawable,它将形状保持在一起,这样我就可以形成更复杂的形状和图形。我发现我必须在渲染时对每个单独的成员形状进行一些更新,这取决于自上次渲染以来 body 整体发生的情况。
这包括:
- 轮换
- 翻译
- 缩放
我想我必须手动编写代码来考虑可能发生在整个 body 上的这些变化,所以形状位置结果是正确的。然而,在对旋转部分进行编码时,我发现在编写手动代码后,即使我使 Bodies Render() 函数仅迭代并渲染每个形状而不更改它们,但它们无论如何都会以正确的方向出现。 这怎么可能?
我注释掉了我编写的显然不需要的代码,并且我使用 Draw() 函数进行渲染。请向我解释一下我的自己的代码!(天哪,我觉得自己很弱智)。
这是类:
class Body : public sf::Drawable{
public:
Body(const sf::Vector2f& Position = sf::Vector2f(0, 0), const sf::Vector2f& Scale = sf::Vector2f(1, 1), float Rotation = 0.f, const sf::Color& Col = sf::Color(255, 255, 255, 255)){
SetPosition(Position);
SetScale(Scale);
SetRotation(Rotation);
SetColor(Col);
RotVal=0;};
////////////////// Drawable Functions ////////////////////
void SetX(float X){
MoveVal.x += X - GetPosition().x;
Drawable::SetX(X);};
void SetY(float Y){
MoveVal.y += Y - GetPosition().y;
Drawable::SetY(Y);};
void SetRotation(float Rotation){
RotVal+= Rotation-GetRotation();
Drawable::SetRotation(Rotation);};
////////////////////////////////////////////////////////////
bool AddShape(sf::Shape& S){
Shapes.push_back(S); return true;};
bool AddSprite(sf::Sprite& S){
Sprites.push_back(S); return true;};
void Draw(sf::RenderTarget& target){
for(unsigned short I=0; I<Shapes.size(); I++){
//Body offset
Shapes[I].SetPosition(
Shapes[I].GetPosition().x + MoveVal.x,
Shapes[I].GetPosition().y + MoveVal.y);
// Aparrently Body shapes rotate on their own...
//WWTFFFF>>>>??????????
//Body Rotation
//float px= GetPosition().x,
// py= GetPosition().y,
// x= Shapes[I].GetPosition().x,
// y= Shapes[I].GetPosition().y,
// rot= ConvToRad(RotVal);
/*Shapes[I].SetPosition(
px + ((x-px)*cos(rot)) - ((y-py)*sin(rot)),
py - ((x-px)*sin(rot)) + ((y-py)*cos(rot)));*/ //TODO: put this in a math header
//Shapes[I].Rotate(RotVal);
}
target.Draw(*this); // draws each individual shape
//Reset all the Change Values
RotVal=0;
MoveVal.x=0;
MoveVal.y=0;
};
private:
sf::Vector2f MoveVal;
float RotVal;
std::vector<sf::Shape> Shapes;
std::vector<sf::Sprite> Sprites;
virtual void Render(sf::RenderTarget& target) const{
for(unsigned short I=0; I<Shapes.size(); I++){
target.Draw(Shapes[I]);}
for(unsigned short I=0; I<Sprites.size(); I++){
target.Draw(Sprites[I]);}
};
};
最佳答案
SFML 源代码证实了我的猜测。
当您调用 target.Draw(*this)
时,它最终会调用 Drawable::Draw(RenderTarget& Target) const
,它会设置一个具有旋转的渲染矩阵你通过 Drawable::SetRotation
调用给它的。然后调用您的 virtual Render
函数,并设置旋转环境。这意味着您的 body 部位会旋转。
自己查看源代码以获得更好的理解。 (;
关于c++ - 我在 SFML : How does it rotate member shapes correctly on its own? 中的 'body' 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6647478/