so://phie

game-engine

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

blob: 99d44aff83aa2fee5191d4ab5eb1762d2191e258 (2551 bytes)[doc][blame][raw]

1import { scaleCanvas } from './canvas.js';

2import * as Collision from './collision.js';

3

4export class Game {

5 constructor(width, height, { fps } = {}) {

6 this.width = width || 900;

7 this.height = height || 600;

8 this.fps = 1000 / (fps || 60);

9 this.then = Date.now();

10 this.canvas = document.createElement('canvas');

11 scaleCanvas(this.canvas, this.width, this.height);

12 this.g = this.canvas.getContext('2d');

13 }

14 start() {

15 requestAnimationFrame(this.loop.bind(this));

16 this.update();

17 this.g.save();

18 this.render(this.g);

19 this.g.restore();

20 }

21 loop() {

22 requestAnimationFrame(this.loop.bind(this));

23 this.now = Date.now();

24 this.elapsed = this.now - this.then;

25 if(this.elapsed > this.fps) {

26 this.then = this.now - (this.elapsed % this.fps);

27 this.update();

28 this.g.save();

29 this.render(this.g);

30 this.g.restore();

31 }

32 }

33 update() {

34 // empty

35 }

36 render() {

37 this.g.clearRect(0, 0, this.width, this.height);

38 }

39}

40

41export class Group {

42 constructor() {

43 this.items = [];

44 }

45 update() {

46 for(let item of this.items) {

47 item.update();

48 }

49 }

50 render(g) {

51 for(let item of this.items) {

52 g.save();

53 item.render(g);

54 g.restore();

55 }

56 }

57 collide() {

58 for(const i of this.items) {

59 i.items = [];

60 i.collided = false;

61 }

62 const duplicate = [];

63 for(const a of this.items) {

64 for(const b of this.items) {

65 if(!duplicate.includes(b)) {

66 if(a !== b) {

67 let collided = false;

68 if(a.shape instanceof Shape.Rect && b.shape instanceof Shape.Rect) {

69 collided = Collision.collideRect(a, b);

70 }

71 else if(a.shape instanceof Shape.Circle && b.shape instanceof Shape.Circle) {

72 collided = Collision.collideCircle(a, b);

73 }

74 else {

75 collided = Collision.collideRectAndCircle(a, b);

76 }

77 if(!a.collided) {

78 a.collided = collided;

79 }

80 if(!b.collided) {

81 b.collided = collided;

82 }

83 if(collided) {

84 if(!a.items.includes(b)) {

85 a.items.push(b);

86 }

87 if(!b.items.includes(a)) {

88 b.items.push(a);

89 }

90 }

91 }

92 }

93 }

94 duplicate.push(a);

95 }

96 }

97 add(item) {

98 this.items.push(item);

99 }

100 get() {

101 return this.items;

102 }

103}

104

105export class Surface {

106 constructor(x, y, shape) {

107 this.x = x;

108 this.y = y;

109 this.shape = shape;

110 }

111 update() {

112 // empty

113 }

114 render() {

115 // empty

116 }

117}

118

119class Rect {

120 constructor(width, height) {

121 this.width = width;

122 this.height = height;

123 }

124}

125

126class Circle {

127 constructor(radius) {

128 this.radius = radius;

129 }

130}

131