Advertisement
pevel

Untitled

Sep 27th, 2022
790
1
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.18 KB | Source Code | 1 0
  1. using System;
  2. using System.Drawing;
  3. using System.Drawing.Drawing2D;
  4. using System.Windows.Forms;
  5.  
  6. namespace GravityBalls
  7. {
  8.     public class WorldModel
  9.     {
  10.         public double BallX;
  11.         public double BallY;
  12.         public double BallRadius;
  13.         public double WorldWidth;
  14.         public double WorldHeight;
  15.         public Color BallColor;
  16.         public int CursorX;
  17.         public int CursorY;
  18.  
  19.         Random rnd = new Random();
  20.  
  21.         public double horizontalSpeed = 400.0;
  22.         public double verticalSpeed = 400.0;
  23.  
  24.         public double coefficientResistance = 0.7;
  25.         public double coefficientAttraction = 0.2;
  26.  
  27.         public void SimulateTimeframe(double dt)
  28.         {
  29.             BallX = Math.Max(BallRadius, Math.Min(BallX + CalculateHorizontalSpeed(horizontalSpeed) * dt, WorldWidth - BallRadius));
  30.             BallY = Math.Max(BallRadius, Math.Min(BallY + CalculateVerticalSpeed(verticalSpeed) * dt, WorldHeight - BallRadius));
  31.             if (BallX >= WorldWidth - BallRadius || BallX <= BallRadius)
  32.             {
  33.                 BallColor = GetRandomColor();
  34.                 horizontalSpeed *= -1;
  35.             }
  36.             if (BallY >= WorldHeight - BallRadius || BallY <= BallRadius)
  37.             {
  38.                 BallColor = GetRandomColor();
  39.                 verticalSpeed *= -1;
  40.             }
  41.         }
  42.  
  43.         private double CalculateHorizontalSpeed(double speed)
  44.         {
  45.             return speed * coefficientResistance + 20 / GetDistanceToCursor();
  46.         }
  47.  
  48.         private double CalculateVerticalSpeed(double speed)
  49.         {
  50.             if (speed >= 0)
  51.                 return speed * coefficientResistance * (1 + coefficientAttraction) + 20 / GetDistanceToCursor();
  52.             return speed * coefficientResistance * (1 - coefficientAttraction) + 20 / GetDistanceToCursor();
  53.         }
  54.  
  55.         private Color GetRandomColor()
  56.         {
  57.             return Color.FromArgb(rnd.Next() % 255, rnd.Next() % 255, rnd.Next() % 255);
  58.         }
  59.  
  60.         private double GetDistanceToCursor()
  61.         {
  62.             return Math.Sqrt((CursorX - BallX) * (CursorX - BallX) + (CursorY - BallY) * (CursorY - BallY));
  63.         }
  64.     }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement