JSFiddle - React, Tailwind, and code Playground

by lastuniverse

HTML

<!DOCTYPE html>
<html>
<head>
  <title>Game</title>
</head>
<body>
<canvas id="canvas" width="500" height="500"></canvas>
</body>
</html>

CSS

#canvas{
  border:1px solid black;
}

JavaScript

const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

const width = canvas.width = 500;
const height = canvas.height = 500;
const cx = width/2;
const cy = height/2;
    
const mass = 200000;
const G = 1;


// класс небесного тела
class Planet {
	constructor(massa=1,addspeed=0.0,scale=1000){
		this.mass = massa;
    this.scale = scale;
    this.color = "black";
    this.addspeed = addspeed;
    this.randomSpawn();
	}

	// цикл обработки
	loop(){
		this.calc();  
  }
  
	// метод случайным образом размещает объект
	randomSpawn(){
		// случайным образом выбираем координаты объекта
		this.dist = this.scale/2 + Math.floor(Math.random()*this.scale/2);
		this.angle = Math.floor(Math.random()*Math.PI*2);

    this.x = Math.cos(this.angle)*this.dist;
    this.y = Math.sin(this.angle)*this.dist;

		// вычисляем первую космическую
    this.speed = Math.sqrt(G*mass/this.dist);
    this.speed = this.speed + this.speed*this.addspeed;
    
		// вычисляем вектор движения
    const q = this.speed/this.dist;
		this.dx = this.y*q;
		this.dy = -this.x*q;
	}


  // пропорциональный метод расчитывает следующие координаты объекта
  calc(){
		// вычисляем вектор движения
    
		this.x += this.dx;
		this.y += this.dy;

    let dist = Math.sqrt(this.x*this.x+this.y*this.y);
      
		// находим коэффициент гравитации
		this.gravity = Math.sqrt(G*mass/(dist*dist));
    
    // находим вектор силы притяжения
    this.tdx = -this.x*this.gravity/dist;
    this.tdy = -this.y*this.gravity/dist;
    
    // вычисляем вектор движения
		this.dx += this.tdx;
		this.dy += this.tdy;
	}

	// метод рисует объект и доп информацию
	draw(){
		// this.ctx.fillRect(food.x-5,food.y-5,10,10);
		ctx.fillStyle = this.color;


		const x = (this.x*width/this.scale + width)/2;
    const y = (this.y*height/this.scale + height)/2;
    
    // объект
		ctx.beginPath();
			ctx.arc( x, y, this.mass, 0, Math.PI * 2);
		ctx.fill();    

		// линию между центром объекта и центром источника...