Last active
August 29, 2015 14:21
-
-
Save dabbertorres/c550b2dde17f95b0bafa to your computer and use it in GitHub Desktop.
Naive Center -> Mouse Position Projectile SFML Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <SFML/Graphics.hpp> | |
#include <SFML/Window.hpp> | |
sf::Vector2f unitVec(const sf::Vector2f& vec); | |
int main(int argc, char** argv) | |
{ | |
sf::RenderWindow window({800, 600}, "Line To Mouse"); | |
window.setVerticalSyncEnabled(true); | |
const sf::Vector2f CENTER = static_cast<sf::Vector2f>(window.getSize() / 2u); | |
constexpr float LENGTH = 35.f; | |
constexpr float VELOCITY = 122.f; | |
sf::VertexArray line(sf::Lines, 2); | |
line[0].position = CENTER; | |
line[0].color = sf::Color::Red; | |
line[1].position = CENTER; | |
line[1].color = sf::Color::Red; | |
bool shot = false; | |
bool update = false; | |
sf::Clock clock; | |
while(window.isOpen()) | |
{ | |
sf::Time dt = clock.restart(); | |
sf::Event event; | |
while(window.pollEvent(event)) | |
{ | |
switch(event.type) | |
{ | |
case sf::Event::Closed: | |
window.close(); | |
break; | |
case sf::Event::KeyPressed: | |
if(event.key.code == sf::Keyboard::Escape) | |
window.close(); | |
break; | |
case sf::Event::MouseEntered: | |
update = true; | |
break; | |
case sf::Event::MouseLeft: | |
update = false; | |
break; | |
case sf::Event::MouseButtonReleased: | |
if(update) | |
{ | |
sf::Vector2f mousePos = {static_cast<float>(event.mouseButton.x), | |
static_cast<float>(event.mouseButton.y)}; | |
sf::Vector2f projEndNorm = unitVec(mousePos - CENTER); | |
line[0].position = CENTER + projEndNorm; // offset from the center slightly so line[0].position - CENTER will != {0, 0} | |
line[1].position = projEndNorm * LENGTH + CENTER; | |
shot = true; | |
} | |
default: | |
break; | |
} | |
} | |
if(shot) | |
{ | |
line[0].position += unitVec(line[0].position - CENTER) * VELOCITY * dt.asSeconds(); | |
line[1].position += unitVec(line[1].position - CENTER) * VELOCITY * dt.asSeconds(); | |
if(line[0].position.x < 0 || line[0].position.x > 800 && line[0].position.y < 0 || line[0].position.y > 600) | |
shot = false; | |
} | |
window.clear(); | |
if(shot) | |
window.draw(line); | |
window.display(); | |
} | |
return 0; | |
} | |
sf::Vector2f unitVec(const sf::Vector2f& vec) | |
{ | |
if(vec.x != 0 && vec.y != 0) | |
return vec / std::sqrt(vec.x * vec.x + vec.y * vec.y); | |
else | |
return {0, 0}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment