【发布时间】:2019-08-21 14:17:51
【问题描述】:
class ShapePlanet
{
public:
sf::CircleShape shape;
sf::Vector2f planetposition;
int radius = 45;
ShapePlanet()
{
float x = rand() % 1020; //invece che 1280
float y = rand() % 650; //invece che 720
this->shape.setFillColor(sf::Color::Green);
this->planetposition.x = x;
this->planetposition.y = y;
this->shape.setPosition(x, y);
}
};
struct Node_Planet
{
ShapePlanet Planet;
Node_Planet* next;
};
typedef Node_Planet* ptr_list;
class Planet
{
private:
ptr_list head;
public:
ptr_list create(int n)
{
ptr_list tmp = NULL;
for (int i = 0; i < n; i = i + 1)
{
{
tmp = new Node_Planet;
tmp->Planet = ShapePlanet();
tmp->next = head;
head = tmp;
}
return this->head;
}
void draw(sf::RenderWindow& window)
{
ptr_list p = this->head;
while (p != NULL)
{
window.draw(p->Planet.shape);
p = p->next;
}
}
void IsItOverLapped()
{
ptr_list p1 = this->head;
ptr_list p2 = this->head;
// bool collision = false;
sf::FloatRect shape1;
sf::FloatRect shape2;
float distance;
float dx;
float dy;
//float distance = std::sqrt((dx * dx) + (dy * dy));
while ((p1 != NULL))
{
//float distance = std::sqrt((dx * dx) + (dy * dy));
while (p2 != NULL)
{
shape1 = p1->Planet.shape.getGlobalBounds();
shape2 = p2->Planet.shape.getLocalBounds();
dx = (p1->Planet.shape.getPosition().x + (shape1.width / 2)) - (p2->Planet.shape.getPosition().x + (shape2.width / 2));
dy = (p1->Planet.shape.getPosition().y + (shape1.height / 2)) - (p2->Planet.shape.getPosition().y + (shape2.height / 2));
distance = std::sqrt((dx * dx) + (dy * dy));
if (distance <= (shape1.width / 2) + (shape2.width / 2))
//if (p2->Planet.shape.getGlobalBounds().intersects(p1->Planet.shape.getLocalBounds()))
{
std::cout << "Collision Detected" << std::endl;
//p2 = p2->next;
//collision = true;
}
else
{
std::cout << "No Collision Detected" << std::endl;
//collision = false;
}
/*if (p2->Planet.shape.getLocalBounds().intersects(p1->Planet.shape.getLocalBounds()))
std::cout << "collision";
std::cout <<'\n'; */
p2 = p2->next;
}
p1 = p1->next;
}
//return collision;
}
}
};
所以,我希望能够在屏幕上绘制形状。问题是我很难检测形状的碰撞。如果我能够检测到碰撞,那么我可以改变重叠形状的位置。但我正在为此苦苦挣扎。 我有一个对象列表。它们有一些特征,如形状、位置等。 我也尝试过使用 if(object1.getLocalBounds.intersects(object2.getLocalbounds()) {then do something} 但似乎代码没有进入 if 方面。我已经尝试了很多次,但我真的没有不知道怎么处理这件事了。
【问题讨论】:
-
请不要typedef指针!这只是来自 MS 的一个坏习惯,只是为了隐藏信息......
-
如果你考虑 round 行星,那么我不会与矩形相交,相反,你可以计算它们中心的距离,如果这个距离小于两个半径之和...
-
我们的教授总是这样做。
-
我尝试计算距离和做半径的事情,但在那种情况下我也失败了。我在网上查了一下,试图找到一些东西,我找到了那个代码,但仍然没有得到任何地方:/
-
嗯,教授养成坏习惯的情况并不少见。他们是专业的or,而不是专业的ional(在开发人员的意义上;我承认他们是专业的老师)...