A lightweight JavaScript game engine
git clone git://soophie.de/game-engine
blob: d2845bac968b39fa421561e3764726096737b233 (914 bytes)[doc][blame][raw]
1
import { Shape } from './game.js';3
export function collideRect(a, b) {4
return a.x < b.x + b.shape.width && a.x + a.shape.width > b.x5
&& a.y < b.y + b.shape.height && a.y + a.shape.height > b.y;6
}8
export function collideCircle(a, b) {9
const dx = Math.abs(a.x - b.x);10
const dy = Math.abs(a.y - b.y);11
return Math.sqrt(dx ** 2 + dy ** 2) < a.shape.radius + b.shape.radius;12
}14
export function collideRectAndCircle(a, b) {15
const [rect, circle] = a instanceof Shape.Rect ? [a, b] : [b, a];16
const dx = Math.abs(circle.x - rect.x);17
const dy = Math.abs(circle.y - rect.y);18
if(dx > rect.shape.width / 2 + circle.radius) {19
return false;20
}21
if(dy > rect.shape.height / 2 + circle.radius) {22
return false;23
}24
if(dx < rect.shape.width / 2) {25
return true;26
}27
if(dy < rect.shape.height / 2) {28
return true;29
}30
return (dx - rect.shape.width / 2) ** 2 + (dy - rect.shape.height / 2) ** 2 < circle.radius ** 2;