Created
January 6, 2022 10:39
-
-
Save blackmann/e7cd5cb931a7fe6925f687b21409e204 to your computer and use it in GitHub Desktop.
Asteroid game with matter js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
Bodies, | |
Body, | |
Common, | |
Composite, | |
Engine, | |
Events, | |
Mouse, | |
Render, | |
Runner, | |
Vector, | |
} from "matter-js"; | |
const RENDER_WIDTH = 400; | |
const RENDER_HEIGHT = 300; | |
export default function main() { | |
// Engine set up | |
const engine = Engine.create(); | |
engine.gravity.y = 0.0; | |
const render = Render.create({ | |
canvas: document.querySelector("#playground"), | |
engine, | |
options: { | |
width: RENDER_WIDTH, | |
height: RENDER_HEIGHT, | |
wireframeBackground: "#333", | |
// showStats: true | |
}, | |
}); | |
Render.run(render); | |
const runner = Runner.create(); | |
Runner.run(runner, engine); | |
// World/objects set up | |
const shipGroup = Body.nextGroup(true); | |
const spaceShip = Bodies.rectangle( | |
RENDER_WIDTH / 2, | |
RENDER_HEIGHT / 2, | |
20, | |
20, | |
{ collisionFilter: { group: shipGroup } } | |
); | |
Composite.add(engine.world, spaceShip); | |
const mouse = Mouse.create(); | |
Composite.add(engine.world, mouse); | |
// | |
Events.on(engine, "afterUpdate", () => { | |
const angle = Vector.angle(spaceShip.position, mouse.position); | |
Body.setAngle(spaceShip, angle); | |
}); | |
Events.on(engine, 'collisionEnd', (event) => { | |
event.pairs.forEach((pair) => { | |
Composite.remove(engine.world, pair.bodyA) | |
Composite.remove(engine.world, pair.bodyB ) | |
}) | |
}) | |
setInterval(() => { | |
const ammo = Bodies.circle(spaceShip.position.x, spaceShip.position.y, 5, { | |
collisionFilter: { group: shipGroup }, | |
}); | |
// 1.56 is callibrated | |
Body.setVelocity( | |
ammo, | |
Vector.rotate(Vector.create(0, 4), spaceShip.angle - 1.56) | |
); | |
Composite.add(engine.world, ammo); | |
}, 500); | |
setInterval(() => { | |
const asteroid = Bodies.circle( | |
Common.random(0, RENDER_WIDTH), | |
Common.random(0, RENDER_HEIGHT), | |
Common.random(10, 50) | |
); | |
Composite.add(engine.world, asteroid) | |
}, 1000); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment