Here's a board game using OGL with a zoomable, draggable hexagon grid featuring water, grass, and sand tiles:
import { Renderer, Camera, Transform, Program, Mesh, Vec2, Vec3, Plane, Raycast } from 'https://cdn.skypack.dev/ogl';
// Initialize renderer
const renderer = new Renderer({
width: window.innerWidth,
height: window.innerHeight,
antialias: true,
});
document.body.appendChild(renderer.gl.canvas);
// Scene setup
const camera = new Camera(renderer.gl);
camera.position.z = 5;
const scene = new Transform();
// Hexagon grid parameters
const gridRadius = 10;
const hexSize = 0.5;
const hexHeight = hexSize * Math.sqrt(3);
const hexWidth = hexSize * 2;
const hexVerticalSpacing = hexHeight;
const hexHorizontalSpacing = hexWidth * 0.75;
// Colors for different tile types
const tileColors = {
water: [0.2, 0.5, 0.8],
grass: [0.3, 0.7, 0.3],
sand: [0.9, 0.8, 0.5]
};
// Create hexagon geometry
function createHexagonGeometry(gl, size) {
const vertices = [];
const uvs = [];
const indices = [];
// Center vertex
vertices.push(0, 0, 0);
uvs.push(0.5, 0.5);
// Outer vertices
for (let i = 0; i < 6; i++) {
const angle = Math.PI / 3 * i;
vertices.push(size * Math.cos(angle), size * Math.sin(angle), 0);
uvs.push(0.5 + 0.5 * Math.cos(angle), 0.5 + 0.5 * Math.sin(angle));
if (i > 0) {
indices.push(0, i, i + 1);
}
}
// Close the hexagon
indices.push(0, 6, 1);
return {
position: { size: 3, data: new Float32Array(vertices) },
uv: { size: 2, data: new Float32Array(uvs) },
index: { data: new Uint16Array(indices) }
};
}
// Generate a random tile type
function getRandomTileType() {
const types = ['water', 'grass', 'sand'];
return types[Math.floor(Math.random() * types.length)];
}
// Create hexagon tiles
const hexagons = [];
const hexGeometry = createHexagonGeometry(renderer.gl, hexSize);
for (let q = -gridRadius; q <= gridRadius; q++) {
const r1 = Math.max(-gridRadius, -q - gridRadius);
const r2 = Math.min(gridRadius, -q + gridRadius);
for (let r = r1; r <= r2; r++) {
const x = hexHorizontalSpacing * q;
const y = hexVerticalSpacing * (r + q/2);
const tileType = getRandomTileType();
const color = tileColors[tileType];
const program = new Program(renderer.gl, {
vertex: `
attribute vec3 position;
attribute vec2 uv;
uniform mat4 modelViewMatrix;
uniform mat4 projectionMatrix;
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,
fragment: `
precision highp float;
uniform vec3 color;
varying vec2 vUv;
void main() {
float dist = distance(vUv, vec2(0.5));
float alpha = smoothstep(0.5, 0.48, dist);
gl_FragColor = vec4(color, alpha);
}
`,
uniforms: {
color: { value: color }
},
transparent: true,
});
const mesh = new Mesh(renderer.gl, { geometry: hexGeometry, program });
mesh.position.set(x, y, 0);
mesh.setParent(scene);
// Store tile data
hexagons.push({
mesh,
position: new Vec3(x, y, 0),
q,
r,
type: tileType,
selected: false
});
}
}
// Interaction handling
const mouse = new Vec2();
const raycaster = new Raycast();
const plane = new Plane();
// For dragging
let isDragging = false;
let previousPosition = new Vec2();
let selectedHexagon = null;
// For zooming
let zoomLevel = 1;
const minZoom = 0.5;
const maxZoom = 3;
// Mouse event handlers
renderer.gl.canvas.addEventListener('mousedown', (e) => {
const rect = renderer.gl.canvas.getBoundingClientRect();
mouse.set(
(e.clientX - rect.left) / rect.width * 2 - 1,
-((e.clientY - rect.top) / rect.height) * 2 + 1
);
previousPosition.set(e.clientX, e.clientY);
isDragging = true;
// Check for hexagon selection
const hits = [];
raycaster.castMouse(camera, mouse, scene, hits);
if (hits.length) {
const hitMesh = hits[0].mesh;
const hexagon = hexagons.find(h => h.mesh === hitMesh);
if (hexagon) {
if (selectedHexagon) {
// Reset previous selection
selectedHexagon.selected = false;
const prevColor = tileColors[selectedHexagon.type];
selectedHexagon.mesh.program.uniforms.color.value = prevColor;
}
// Select new hexagon
selectedHexagon = hexagon;
hexagon.selected = true;
// Highlight selected hexagon
const baseColor = tileColors[hexagon.type];
const highlightColor = baseColor.map(c => Math.min(c + 0.2, 1.0));
hexagon.mesh.program.uniforms.color.value = highlightColor;
console.log(`Selected hexagon: q=${hexagon.q}, r=${hexagon.r}, type=${hexagon.type}`);
}
}
});
renderer.gl.canvas.addEventListener('mousemove', (e) => {
if (!isDragging) return;
const deltaX = e.clientX - previousPosition.x;
const deltaY = e.clientY - previousPosition.y;
// Scale movement based on zoom level
scene.position.x += deltaX * 0.005 / zoomLevel;
scene.position.y -= deltaY * 0.005 / zoomLevel;
previousPosition.set(e.clientX, e.clientY);
});
renderer.gl.canvas.addEventListener('mouseup', () => {
isDragging = false;
});
renderer.gl.canvas.addEventListener('wheel', (e) => {
e.preventDefault();
// Adjust zoom level
zoomLevel -= e.deltaY * 0.001;
zoomLevel = Math.max(minZoom, Math.min(maxZoom, zoomLevel));
// Apply zoom
camera.position.z = 5 / zoomLevel;
});
// Handle window resize
window.addEventListener('resize', () => {
renderer.setSize(window.innerWidth, window.innerHeight);
camera.perspective({ aspect: window.innerWidth / window.innerHeight });
});
// Animation loop
function animate() {
requestAnimationFrame(animate);
renderer.render({ scene, camera });
}
animate();
Would you like me to explain or break down the code?