From 9be73c2d0f21a539bc46974139e8c36c12845ca0 Mon Sep 17 00:00:00 2001 From: Fbenas Date: Sun, 20 Sep 2020 22:08:03 +0100 Subject: Initial commit --- resources/js/component.js | 80 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 resources/js/component.js (limited to 'resources/js/component.js') diff --git a/resources/js/component.js b/resources/js/component.js new file mode 100644 index 0000000..6d74e93 --- /dev/null +++ b/resources/js/component.js @@ -0,0 +1,80 @@ +class Component { + + constructor(radius, color, x, y, direction) { + this.perceptionDistance = 20; + this.turnStepAmount = 5; + this.collisionTurnStepAmount = 20; + this.stepAmount = 1; + this.radius = radius; + this.x = x; + this.y = y; + this.direction = direction; + this.color = color; + } + + move(context) { + this.direction += Math.random() * (2 * this.turnStepAmount) - this.turnStepAmount + var localDirection = this.direction; + // first we need to work out if we detect any walls + var perceptionVector = this.detectionPoint(this.x, this.y, this.perceptionDistance, localDirection); + + while (perceptionVector.x < 0 || perceptionVector.y < 0 || perceptionVector.x > context.canvas.width || perceptionVector.y > context.canvas.height) { + localDirection += Math.random() * (2 * this.collisionTurnStepAmount) - this.collisionTurnStepAmount + perceptionVector = this.detectionPoint(this.x, this.y, this.perceptionDistance, localDirection); + } + + // Here we should now have a new vector that's not clipping + this.direction = localDirection; + var vector = this.detectionPoint(this.x, this.y, this.stepAmount, this.direction); + + + this.x = vector.x; + this.y = vector.y; + this.update(context); + } + + update(context) { + context.beginPath(); + context.fillStyle = "blue"; + context.arc(this.x, this.y, this.radius, 0, 2 * Math.PI); + context.stroke(); + + context.restore(); + context.beginPath(); + this.lineToAngle(context, this.x, this.y, this.perceptionDistance, this.direction); + context.lineWidth = 1; + // context.stroke(); + + context.restore(); + } + + lineToAngle(context, x1, y1, length, angle) { + + angle *= Math.PI / 180; + + var x2 = x1 + length * Math.cos(angle), + y2 = y1 + length * Math.sin(angle); + + context.moveTo(x1, y1); + context.lineTo(x2, y2); + + return { + x: x2, + y: y2 + }; + } + + detectionPoint(x1, y1, length, angle) { + + angle *= Math.PI / 180; + + var x2 = x1 + length * Math.cos(angle), + y2 = y1 + length * Math.sin(angle); + + return { + x: x2, + y: y2 + }; + } + +} -- cgit v1.2.3