JSFiddle - React, Tailwind, and code Playground

by Brenton Strine

HTML

<canvas class="world"></canvas>

CSS

canvas { border: 1px solid black; }

JavaScript

var world = document.querySelector(".world");
var worldWidth = 500;
var worldHeight = 500;

var Render = function () {
  if (world.getContext) {
    var ctx = world.getContext('2d');
		// draw crosshairs
    ctx.fillRect(230, 250, 40, 1);
    ctx.fillRect(250, 230, 1, 40);
	}
  
  //correct the x coordinates
  var cx = function cx(x){
    return x + (worldWidth/2);
  }

	// correct the y coordinates
  var cy = function cy(y){
    return ((y * -1) + (worldHeight/2));
  }
  
  return {
    rect: function (x,y,w,h) {
      ctx.fillRect(cx(x), cy(y), w, h);
    },
    fillStyle: function (style) {    
	  	ctx.fillStyle = style;
    },
  };
};

var setupWorld = function() {
  world.setAttribute("width", worldWidth);
  world.setAttribute("height", worldHeight);

};

var fuel = 20;
var position = {x:0, y: 100};
var velocity = {x:0, y:0};
var thrust = {x:2, y:2};
var gravityVector = {x:null, y:null};
var gravityForce = -1;

var dotW = 1;
var dotH = 1;
var dotColor = "green";

function tick() {
	console.log("tick");
  calculateVelocity();
  renderTick();
}

var calculateVelocity = function () {
	// no thrust if not enough fuel
  var totalThrust = thrust.x + thrust.y;
  if (fuel > totalThrust) {
	  fuel = fuel - totalThrust;
  } else {
	  dotColor = "red";
    thrust = {x:0, y:0};
  }

	gravityVector = getGravityVector();
  console.log(gravityVector);
  
  // update velocity
	velocity.x = velocity.x + thrust.x + gravityVector.x;
	velocity.y = velocity.y + thrust.y + gravityVector.y;
  
  // update position
	position.x = position.x + velocity.x; 
	position.y = position.y + velocity.y; 

};

var renderTick = function (){
	var render = new Render();
  render.fillStyle (dotColor);
  render.rect(position.x, position.y, dotW, dotH);
};

var getGravityVector = function (){
	var totalVectorLength = Math.abs(position.x) + Math.abs(position.y);
  var xPercent = position.x / totalVectorLength;
  var yPercent = position.y / totalVectorLength;
  
  return {
    x: xPercent *...