Easy and cool game engine made with JavaScript!
<script src="https://raw.githubusercontent.com/OguzhanUmutlu/JavaScript2D/main/script.js"></script>
- Install
2d-canvas-game
as dependency first!
const {Vector2, ImageModel, SquareModel, TextModel, EntityData, Entity, Scene} = require("canvas-game-2d");
- You can install it to your IDE by holding your mouse on it and clicking
Download library
<canvas style="outline: black 3px solid;" id="canvas" width="500" height="500"></canvas>
<script>
const canvas = document.getElementById("canvas");
const scene = new Scene(canvas);
</script>
const { createCanvas } = require("canvas");
const canvas = createCanvas(500, 500);
const scene = new Scene(canvas);
const player = new Entity(
new EntityData()
.setX(0) // spawn position of player
.setY(0)
.setModel(new SquareModel(20, 20)) // width, height
);
scene.addEntity(player);
const heldKeys = {};
addEventListener("keydown", key => {
heldKeys[key.key] = true;
});
addEventListener("keyup", key => {
delete heldKeys[key.key];
});
setInterval(() => {
let dx = 0;
let dy = 0;
if (heldKeys["w"]) dy--;
if (heldKeys["a"]) dx--;
if (heldKeys["s"]) dy++;
if (heldKeys["d"]) dx++;
player.x += dx;
player.y += dy; // simply change player's position
});
setInterval(() => {
let dx = 0;
let dy = 0;
if (heldKeys["w"]) dy--;
if (heldKeys["a"]) dx--;
if (heldKeys["s"]) dy++;
if (heldKeys["d"]) dx++;
player.x += dx;
player.y += dy;
player.preventBorder(scene);
});
class Obstacle extends Entity {
}
scene.addEntity(new Obstacle(
new EntityData()
.setX(50)
.setY(50)
.setModel(new SquareModel(20, 20))
));
setInterval(() => {
let dx = 0;
let dy = 0;
if (heldKeys["w"]) dy--;
if (heldKeys["a"]) dx--;
if (heldKeys["s"]) dy++;
if (heldKeys["d"]) dx++;
player.x += dx;
if (player.getCollidingEntities(scene, [Obstacle]).length > 0) player.x -= dx;
player.y += dy;
if (player.getCollidingEntities(scene, [Obstacle]).length > 0) player.y -= dy;
player.preventBorder(scene);
});
const text = new Entity(
new EntityData()
.setX(30)
.setY(30)
.setModel(
new TextModel(10, 10) // width, height
.setText("Hello World!") // text of model
.setFont("Impact") // font of text
.setColor("rgba(0, 255, 0, 0.5)") // color of text
.setPixels(16) // size of the text
.setMaxWidth(100) // maximum size of the text
)
);
scene.addEntity(text);
text.model.setText("Bye World!");