mirror of
https://github.com/Floriansylvain/SFMLplayground.git
synced 2026-08-19 19:53:25 +02:00
feat: velocity tracking w/ rendering lines
This commit is contained in:
+39
-1
@@ -1,8 +1,8 @@
|
||||
#include "Game.hpp"
|
||||
|
||||
#include <SFML/Window/Event.hpp>
|
||||
#include <cmath>
|
||||
|
||||
#include "Ball.hpp"
|
||||
#include "Constants.hpp"
|
||||
#include "VectorMath.hpp"
|
||||
|
||||
@@ -61,9 +61,47 @@ void Game::update() {
|
||||
for (auto& object : m_objects) object->update(dt);
|
||||
}
|
||||
|
||||
void Game::drawLine(const sf::Vector2f& start, const sf::Vector2f& direction,
|
||||
float length, const sf::Color& color) {
|
||||
float dirLength =
|
||||
std::sqrt(direction.x * direction.x + direction.y * direction.y);
|
||||
sf::Vector2f dirNorm =
|
||||
(dirLength != 0.f) ? direction / dirLength : sf::Vector2f(1.f, 0.f);
|
||||
sf::Vector2f endPoint = start + dirNorm * length;
|
||||
|
||||
sf::Vertex line[] = {{start, color}, {endPoint, color}};
|
||||
m_window.draw(line, 2, sf::PrimitiveType::Lines);
|
||||
}
|
||||
|
||||
void Game::drawDirectionLine(const Ball* ball) {
|
||||
sf::Vector2f ballCenter = ball->getPosition();
|
||||
sf::Vector2i mousePixel = sf::Mouse::getPosition(m_window);
|
||||
sf::Vector2f mouseWorld(static_cast<float>(mousePixel.x),
|
||||
static_cast<float>(mousePixel.y));
|
||||
sf::Vector2f dir = mouseWorld - ballCenter;
|
||||
drawLine(ballCenter, dir, 100.f, sf::Color::Green);
|
||||
}
|
||||
|
||||
void Game::drawVelocityLine(const Ball* ball) {
|
||||
if (ball->isAtRest()) return;
|
||||
sf::Vector2f ballCenter = ball->getPosition();
|
||||
sf::Vector2f velocity = ball->getVelocity();
|
||||
float velLength =
|
||||
std::sqrt(velocity.x * velocity.x + velocity.y * velocity.y);
|
||||
float clampedLength = std::min(100.f, std::max(0.f, velLength));
|
||||
drawLine(ballCenter, velocity, clampedLength, sf::Color::Blue);
|
||||
}
|
||||
|
||||
void Game::render() {
|
||||
m_window.clear(sf::Color::Black);
|
||||
for (auto& object : m_objects) object->draw(m_window);
|
||||
|
||||
auto* ball = dynamic_cast<Ball*>(m_objects[0].get());
|
||||
if (ball) {
|
||||
drawDirectionLine(ball);
|
||||
drawVelocityLine(ball);
|
||||
}
|
||||
|
||||
m_window.display();
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user