99 lines
2.3 KiB
TypeScript
99 lines
2.3 KiB
TypeScript
import { initializeContext, Vec2 } from "./common.js";
|
|
import { Graphics, fullscreenCanvas } from "./graphics.js";
|
|
import * as drawing from "./draw.js";
|
|
|
|
const vertexShader =
|
|
`#version 300 es
|
|
|
|
in vec2 a_position;
|
|
in vec4 a_color;
|
|
out vec4 color;
|
|
uniform vec2 u_resolution;
|
|
|
|
void main() {
|
|
vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0;
|
|
|
|
color = a_color;
|
|
|
|
gl_Position = vec4(clipSpace.xy, 0.0, 1.0);
|
|
}
|
|
`;
|
|
|
|
const fragmentShader =
|
|
`#version 300 es
|
|
|
|
precision highp float;
|
|
in vec4 color;
|
|
out vec4 outColor;
|
|
|
|
void main() {
|
|
outColor = color;
|
|
}
|
|
`;
|
|
|
|
|
|
|
|
function draw(gfx: Graphics, dt: number, pos: Vec2, velocity: Vec2) {
|
|
gfx.clear(0, 0, 0, 0);
|
|
gfx.ctx.uniform2f(gfx.getUniform("u_resolution"), gfx.ctx.canvas.width, gfx.ctx.canvas.height);
|
|
drawing.drawCircle(gfx, pos, 200, [1, 0, 0, 1]);
|
|
|
|
if (pos.x + 200 >= gfx.ctx.canvas.width)
|
|
{
|
|
pos.x = gfx.ctx.canvas.width - 200;
|
|
velocity.x *= -1;
|
|
} else if (pos.x - 200 <= 0)
|
|
{
|
|
pos.x = 200;
|
|
velocity.x *= -1;
|
|
}
|
|
|
|
if (pos.y + 200 >= gfx.ctx.canvas.height)
|
|
{
|
|
pos.y = gfx.ctx.canvas.height - 200;
|
|
velocity.y *= -1;
|
|
} else if (pos.y - 200 <= 0)
|
|
{
|
|
pos.y = 200;
|
|
velocity.y *= -1;
|
|
}
|
|
|
|
pos.add(velocity.multNew(dt));
|
|
}
|
|
|
|
(() => {
|
|
const canvasId = "game";
|
|
const ctx = initializeContext(canvasId);
|
|
if (ctx === null) return;
|
|
|
|
const gfx = new Graphics(ctx, vertexShader, fragmentShader);
|
|
fullscreenCanvas(gfx, canvasId);
|
|
|
|
const a_position = gfx.createAttribute("a_position");
|
|
a_position.format(2, gfx.ctx.FLOAT, false, 0, 0);
|
|
|
|
const a_color = gfx.createAttribute("a_color");
|
|
a_color.format(4, gfx.ctx.FLOAT, false, 0, 0);
|
|
|
|
gfx.createUniform("u_resolution");
|
|
|
|
let pos = new Vec2(300, 300);
|
|
let velocity = new Vec2(200, 200);
|
|
|
|
let prevTimestamp = 0;
|
|
const frame = (timestamp: number) => {
|
|
const deltaTime = (timestamp - prevTimestamp)/1000;
|
|
prevTimestamp = timestamp;
|
|
|
|
fullscreenCanvas(gfx, "game");
|
|
draw(gfx, deltaTime, pos, velocity);
|
|
|
|
window.requestAnimationFrame(frame);
|
|
}
|
|
|
|
window.requestAnimationFrame((timestamp) => {
|
|
prevTimestamp = timestamp;
|
|
window.requestAnimationFrame(frame);
|
|
});
|
|
})();
|