@Override
	public void run()
	{
		long cycleStartTime = 0;
		long cycleStopTime = 0;

		// Infinite loop is the best way to implement this?
		while(true)
		{
			// repaint the scene!
			repaint();
			
			// Currently we just sleep the engine to imitate speed, this
			// will be changed once we create vector graphics instead.
			try
			{
				Thread.sleep( Math.max(0, engineSettings.getSpeed() - (cycleStopTime - cycleStartTime)));
			}
			catch (InterruptedException e)
			{
				e.printStackTrace();
			}

			cycleStartTime = System.currentTimeMillis();
			
			ArrayList<Ball> tmpBalls = new ArrayList<>();
			
			for(EngineEntity e : entities.values())
				if(e instanceof Ball)
					tmpBalls.add((Ball) e);
			
			// Call collision on all found colliding balls.
			CollisionsEngine.findCollisions(tmpBalls).forEach(Ball::collision);
			
			for(Iterator<Map.Entry<Integer, EngineEntity>> it = entities.entrySet().iterator(); it.hasNext();)
			{
				Map.Entry<Integer, EngineEntity> entry = it.next();
				if(!entry.getValue().isAlive())
					it.remove();
			}
			
			for(EngineEntity e : entities.values())
			{
				if(e instanceof Ball && !(e instanceof Projectile))
				{
					Ball tmp = (Ball)e;
					if(tmp.getY() > engineSettings.getHeight())
					{
						//JOptionPane.showConfirmDialog(null, "You lost!");
						//tmp.setAlive(false);
					}
				}
			}
			
			// Actually move the balls now that we've found and corrected
			// all the collisions.
			for(EngineEntity e : entities.values())
				e.move();
			
			cycleStopTime = System.currentTimeMillis();
		}
	}