#include <SFML/Graphics.hpp>
#include <cmath>
#include <iostream>

#define M_PI 3.14159265359

int main()
{
	sf::RenderWindow window(sf::VideoMode(800, 600), "Projectile launched by a spring");


	sf::CircleShape projectile(10.0f);

	projectile.setFillColor(sf::Color::Red);
	projectile.setOrigin(projectile.getRadius(), projectile.getRadius());

	sf::Vector2f position(100, 500);
	projectile.setPosition(position);


	//spring and projectile physics paramaters

	float springConstant = 500000.0f; //spring constant (n/m)
	float compressionDistance = 0.3f;
	float mass = 0.5f;
	float gravity = 9.81f;
	bool launched = false;

	float initialVelocity = std::sqrt((springConstant * compressionDistance * compressionDistance) / mass);


	sf::Vector2f velocity(
		initialVelocity * std::cos(45.0f * M_PI / 180.0f),
		-initialVelocity * std::sin(45.0f * M_PI / 180.0f));


	sf::Clock clock;

	while(window.isOpen())
	{
		sf::Event event;
		while(window.pollEvent(event))
		{
			if (event.type == sf::Event::Closed) window.close();

			if(event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Space && !launched)
			{
				launched = true;
			}
		}
		////////////////////////////////////////////////////////////////////////////////////////////////////////

		float deltaTime = clock.restart().asSeconds();

		if(launched)
		{
			position += velocity * deltaTime;
			velocity.y += gravity * deltaTime;
		}
		else
		{
			projectile.setPosition(position - sf::Vector2f(compressionDistance * 100.0f, 0.0f));
		}



		if(position.y > window.getSize().y - projectile.getRadius())
		{
			position.y = window.getSize().y - projectile.getRadius();
			velocity.y *= -0.5f;
		}

		if (position.x > window.getSize().x - projectile.getRadius())
		{
			position.x = window.getSize().x - projectile.getRadius();
			velocity.x *= -0.5f;
		}

		window.clear(sf::Color::White);
		projectile.setPosition(position);
		window.draw(projectile);
		window.display();
	}



}
