JSFiddle - React, Tailwind, and code Playground
by caub
HTML
<div id="pos"> </div>
<canvas id="canvas"></canvas>
CSS
canvas {
display: block;
}
JavaScript
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
width = canvas.width = window.innerWidth,
height = canvas.height = window.innerHeight,
centerX = width / 2,
centerY = height / 2,
pow2 = x=>Math.pow(x,2),
sqrt = Math.sqrt, cos = Math.cos, sin = Math.sin, atan2 = Math.atan2, pi = Math.PI, sign = Math.sign;
function dist(a, b){
return sqrt(pow2(a.x-b.x)+pow2(a.y-b.y))
}
function mod(x, value){ // Euclidean modulo http://jsfiddle.net/cLvmrs6m/4/
return x>=0 ? x%value : value+ x%value;
} // for comparing angles the right way
function angularize(x){
return mod(x+pi, 2*pi)-pi;
}
var player = {
pos: {x:0, y:0},
angle: 1.5*pi,
shieldradius: 100,
shieldwidth: .3*pi,
radius: 30,
}
var enemy = {
pos: {x:+100, y:+55},
angle: 0.25*pi+pi,
radius: 20,
speed: 0,
destroyed: false
}
function start() {
// check intersection of shield arc with enemy
if(true/*!enemy.destroyed*/){
var d_enemy_player = dist(enemy.pos, player.pos)
if (d_enemy_player>player.shieldradius-enemy.radius && d_enemy_player<player.shieldradius+enemy.radius){ // worth checking
var angle_enemy_from_player = atan2(enemy.pos.y-player.pos.y, enemy.pos.x-player.pos.x)
console.log('>',angle_enemy_from_player, player.angle)
var delta_with_leftofshield = angularize(angle_enemy_from_player-player.angle-player.shieldwidth)
var delta_with_rightofshield = angularize(angle_enemy_from_player-player.angle+player.shieldwidth)
var delta_with_shield = angularize(angle_enemy_from_player-player.angle)
console.log(delta_with_leftofshield, delta_with_rightofshield)
if (sign(delta_with_leftofshield)<0 && sign(delta_with_rightofshield)>0){
console.log('boo')
enemy.destroyed = true;
}else if(sign(delta_with_shield)>=0 ){ // check distance with right extremety of arc
...