so://phie

game-engine

A lightweight JavaScript game engine
git clone git://soophie.de/game-engine

blob: 7a5c4a899f4255510fd85ac31c20b28839eafea6 (1301 bytes)[doc][blame][raw]

1import { Shape } from './game.js';

2

3export function collideRect(a, b) {

4 return a.x < b.x + b.shape.width && a.x + a.shape.width > b.x

5 && a.y < b.y + b.shape.height && a.y + a.shape.height > b.y;

6}

7

8export 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}

13

14export 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;

31}

32

33export function collidePoint(object, point) {

34 if(object.shape instanceof Shape.Rect) {

35 const {x, y, shape: {width, height}} = object;

36 return x < point.x && x + width > point.x && y < point.y && y + height > point.y;

37 }

38 if(object.shape instanceof Shape.Circle) {

39 const {x, y, shape: {radius}} = object;

40 return Math.sqrt((x - point.x) ** 2 + (y - point.y) ** 2) < radius;

41 }

42}