JSFiddle - React, Tailwind, and code Playground
HTML
<html>
<head>
<title>Bike</title>
<style>
#canvas {
border: 1px solid black;
}
</style>
<script type="text/javascript">
// Simple vector class
function Vector(x, y) {
this.x = x
this.y = y
this.set = function(v) {
this.x = v.x
this.y = v.y
}
this.lengthSquared = function() {
return Math.pow(this.x, 2) + Math.pow(this.y, 2)
}
this.length = function() {
return Math.sqrt(this.lengthSquared())
}
this.scale = function(s) {
return new Vector(this.x * s, this.y * s)
}
this.sub = function(v) {
return new Vector(this.x - v.x, this.y - v.y)
}
this.add = function(v) {
return new Vector(this.x + v.x, this.y + v.y)
}
this.dot = function(v) {
return this.x * v.x + this.y * v.y
}
this.dist = function(v) {
return this.sub(v).length()
}
this.normalize = function() {
return this.scale(1/this.length())
}
this.angle = function(v) {
return this.dot(v)/(this.length*v.length)
}
this.toString = function() {
return "(" + this.x + ", " + this.y + ")"
}
}
function Line(x1, y1, x2, y2) {
var p1 = new Vector(x1, y1)
var p2 = new Vector(x2, y2)
var piece = p2.sub(p1)
var sqrLength = piece.lengthSquared()
var prevNearestPoint = new Vector
this.draw = function() {
ctx.beginPath()
ctx.strokeStyle = "rgb(0,0,0)"
ctx.moveTo(p1.x, p1.y)
ctx.lineTo(p2.x, p2.y)
ctx.stroke()
}
var nearestPoint = function(pos) {
var normalizedProjection = pos.sub(p1).dot(piece)
if (normalizedProjection < 0)
return p1
else if (normalizedProjection > sqrLength)
return p2
else // Projection is on line
return p1.add((piece.scale(normalizedProjection / sqrLength)))
}
this.checkCollision = function() {
for (var i = 0; i < wheels.wheels.length; i++)
...