我试图使用Box2D让物理在SFML中工作,但由于某种原因,我无法在我的班级中设置我的精灵的位置。
我为我的游戏创建了一个TestBox,基本上只是一个有物理的盒子,但它似乎并没有起作用。我能够在我的类构造函数中设置框的位置,但不能在我创建的更新函数中设置。
所以代码:
TestBox.h:
#pragma once
#include<Box2D/Box2D.h>
#include<SFML/Graphics.hpp>
#include<string>
#include<iostream>
class TestBox : public sf:: Drawable
{
public:
TestBox(b2World *world, std::string texturePath, float x, float y, float w, float h);
void update();
b2Body *getBody() { return body; }
b2Fixture *getFixture() { return fixture; }
private:
virtual void draw(sf::RenderTarget &target, sf::RenderStates states) const;
b2Body *body = nullptr;
b2Fixture *fixture = nullptr;
sf::Texture texture;
sf::Sprite boxSprite;
};
TestBox.cpp:
#include "TestBox.h"
TestBox::TestBox(b2World *world, std::string texturePath, float x, float y, float w, float h) {
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
bodyDef.position.Set(x, y);
body = world->CreateBody(&bodyDef);
b2PolygonShape boxShape;
boxShape.SetAsBox(w / 2.0f, h / 2.0f);
b2FixtureDef fixtureDef;
fixtureDef.shape = &boxShape;
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.3f;
fixture = body->CreateFixture(&fixtureDef);
texture.loadFromFile(texturePath.c_str());
boxSprite.setTexture(texture);
boxSprite.setOrigin(16.f, 16.f);
boxSprite.setPosition(30.0f * body->GetPosition().x, 30.0f * body->GetPosition().y);
boxSprite.setRotation(body->GetAngle() * 180 / b2_pi);
}
void TestBox::update() {
std::cout << boxSprite.getPosition().x << ", " << boxSprite.getPosition().y << std::endl;
boxSprite.setPosition(30.0f * body->GetPosition().x, 30.0f * body->GetPosition().y);
boxSprite.setRotation(body->GetAngle() * 180 / b2_pi);
}
void TestBox::draw(sf::RenderTarget &target, sf::RenderStates states) const {
target.draw(boxSprite, states);
}
所以,我试图尽可能地缩小我的问题范围,尽可能地统治我的问题。这是我发现的:
我检查过数学:
30.0f * body-&gt; GetPosition()。x
30.0f * body-&gt; GetPosition()。y
这是准确无误的。
更新功能运行,正常打印。
如果我遗漏了您可能需要的任何信息,请告诉我。