Untitled

mail@pastecode.io avatar
unknown
plain_text
25 days ago
1.5 kB
7
Indexable
Never
using System;
using System.Windows.Forms;

namespace GravityBalls
{
	public class WorldModel
	{
		public double BallX;
		public double BallY;
		public double BallRadius;
		public double WorldWidth;
		public double WorldHeight;
		public double BallVx = 400;
		public double BallVy = 300;
		public double Resistance = 0.2;
		public double G = 500;
		public double Force = 300000;

		private void ApplyCursorRepulsion(double dt){
			var cursorX = Cursor.Position.X;
			var cursorY = Cursor.Position.Y;
			var dx = BallX - cursorX;
			var dy = BallY - cursorY;
			var d = Math.Sqrt(dx * dx + dy * dy);
			var f = Force / (d * d);

			BallVx += dx * f * dt;
			BallVy += dy * f * dt;
		}

		private void ApplyGravity(double dt){
			BallVy += G * dt;
		}

		private void ApplyAirResistance(double dt){
			BallVx = BallVx - BallVx * Resistance * dt;
			BallVy = BallVy - BallVy * Resistance * dt;
		}

		public void SimulateTimeframe(double dt){
			MoveBall(dt);
			ApplyWallsBouncing();
			ApplyAirResistance(dt);
			ApplyGravity(dt);
			ApplyCursorRepulsion(dt);
		}

		public void MoveBall(double dt)
		{
			
			BallY = Math.Min(BallY + BallVy*dt, WorldHeight - BallRadius);
			BallX = Math.Min(BallX + BallVx*dt, WorldHeight - BallRadius);
		}

		private void ApplyWallsBouncing(){
			if (BallY + BallRadius >= WorldHeight || BallY - BallRadius <= 0)
				BallVy = -BallVy;
			if (BallX + BallRadius >= WorldWidth || BallX - BallRadius <= 0)
				BallVx = -BallVx;
		}
	}
}