so://phie

game-engine

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

blob: 653b071ffd81992c1243bf456d0521afcdd63c27 (1288 bytes)[doc][blame][raw]

1import { Shape } from './shape.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 let x = circle.x;

17 let y = circle.y;

18 if(circle.x < rect.x) {

19 x = rect.x;

20 }

21 else if(circle.x > rect.x + rect.shape.width) {

22 x = rect.x + rect.shape.width;

23 }

24 if(circle.y < rect.y) {

25 y = rect.y;

26 }

27 else if(circle.y > rect.y + rect.shape.height) {

28 y = rect.y + rect.shape.height;

29 }

30 const distance = Math.sqrt((circle.x - x) ** 2 + (circle.y - y) ** 2);

31 return distance <= circle.shape.radius;

32}

33

34export function collidePoint(object, point) {

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

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

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

38 }

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

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

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

42 }

43}