Обработка коллизии только в том случае если палец на экране c++ sfml
Проблема такова: написал код для перемещения шарика к пальцу на экране, но при добавлении коллизий произошли проблемы. Коллизия как бы работает, то только тогда когда на экране нет пальца. Когда он есть и я перемещаю объект, коллизия игнорируется. Вот код
#include <SFML/Graphics.hpp>
#include <iostream>
#include <cmath>
using namespace sf;
int main()
{
RenderWindow window(VideoMode(360, 800), "SFML", Style::Default);
Vector2u wSize = window.getSize();
int centerX = wSize.x / 2;
int centerY = wSize.y / 2;
CircleShape shape(76.f, 30);
shape.setFillColor(Color::Red);
shape.setOrigin(shape.getRadius(), shape.getRadius());
shape.setPosition(centerX, centerY);
CircleShape shape2(76.f, 30);
shape2.setFillColor(Color::Red);
shape2.setOrigin(shape2.getRadius(), shape2.getRadius());
shape2.setPosition(centerX, centerY / 2);
float radiusSum = shape.getRadius() + shape2.getRadius();
float radius = shape2.getRadius();
while (window.isOpen())
{
Event event;
unsigned int const idx{ 0 };
sf::Vector2i rpos{ Touch::getPosition(idx, window) };
Vector2f pos = window.mapPixelToCoords(rpos);
// Обработка столкновений
Vector2f distance = shape.getPosition() - shape2.getPosition();
float length = std::sqrt(distance.x * distance.x + distance.y * distance.y);
if (length < radiusSum)
{
// Обработка столкновения
Vector2f collisionVector = distance / length;
shape.setPosition(shape.getPosition() + collisionVector * (radiusSum - length));
}
if (::sf::Touch::isDown(idx))
{
if(shape.getGlobalBounds().contains(pos))
{
shape.setPosition(pos.x, pos.y);
}
}
while (window.pollEvent(event))
{
if (event.type == Event::Closed)
window.close();
}
window.clear();
window.draw(shape);
window.draw(shape2);
window.display();
}
}
Источник: Stack Overflow на русском