C'est surtout la ligne "velocity = velocity / length(velocity) * speed; "que je ne comprends pas.
#include "Game.hpp"
using namespace std;
const float Game::PlayerSpeed = 100.f;
const sf::Time Game::TimePerFrame = sf::seconds(1.f/60.f);
Game::Game() : m_window(sf::VideoMode(640, 480), "ILDR"), m_player()
{
m_player.setRadius(10.f);
m_player.setPosition(100.f, 100.f);
m_player.setFillColor(sf::Color::Cyan);
m_isMovingDown = false;
m_isMovingLeft = false;
m_isMovingRight = false;
m_isMovingUp = false;
m_moving = false;
}
void Game::run()
{
sf::Clock clock;
sf::Time timeSinceLastUpdate = sf::Time::Zero;
while(m_window.isOpen())
{
sf::Time deltaTime = clock.restart();
processEvents();
timeSinceLastUpdate += clock.restart();
while(timeSinceLastUpdate > TimePerFrame)
{
timeSinceLastUpdate -= TimePerFrame;
processEvents();
update(TimePerFrame);
}
render();
}
}
void Game::processEvents()
{
sf::Event event;
while(m_window.pollEvent(event))
{
switch(event.type)
{
case sf::Event::KeyPressed:
handlePlayerInput(event.key.code, true);
break;
case sf::Event::KeyReleased:
handlePlayerInput(event.key.code, false);
break;
case sf::Event::Closed:
m_window.close();
break;
case sf::Event::MouseButtonPressed:
}
if(event.type == sf::Event::MouseButtonPressed && event.mouseButton.button == sf::Mouse::Right)
{
sf::Vector2i cursor(event.mouseButton.x, event.mouseButton.y);
target = m_window.mapPixelToCoords(cursor);
velocity = target - m_player.getPosition();
velocity = velocity / length(velocity) * PlayerSpeed;
m_moving = true;
}
}
}
void Game::update(sf::Time elapsedTime)
{
sf::Vector2f movement(0.f, 0.f);
if(m_moving == false)
{
if(m_isMovingUp)
movement.y -= PlayerSpeed;
if(m_isMovingDown)
movement.y += PlayerSpeed;
if(m_isMovingLeft)
movement.x -= PlayerSpeed;
if(m_isMovingRight)
movement.x += PlayerSpeed;
m_player.move(movement * elapsedTime.asSeconds());
}
if(m_moving)
{
m_player.move(velocity * elapsedTime.asSeconds());
if (length(target - m_player.getPosition()) < 5)
m_moving = false;
}
}
void Game::render()
{
m_window.clear();
m_window.draw(m_player);
m_window.display();
}
void Game::handlePlayerInput(sf::Keyboard::Key key, bool isPressed)
{
if(key == sf::Keyboard::Z)
m_isMovingUp = isPressed;
else if(key == sf::Keyboard::S)
m_isMovingDown = isPressed;
else if(key == sf::Keyboard::Q)
m_isMovingLeft = isPressed;
else if(key == sf::Keyboard::D)
m_isMovingRight = isPressed;
}
float Game::length(sf::Vector2f v)
{
return sqrt(v.x * v.x + v.y + v.y);
}