Build a polished browser-based voxel sandbox game website inspired by classic…
- User
Build a polished browser-based voxel sandbox game website inspired by classic block-building survival games, using original branding, textures, icons, and interface elements. Create a playable first-person demo with:
Procedurally generated block terrain with grass, dirt, stone, sand, water, trees, hills, and caves WASD movement, mouse-look, jumping, sprinting, gravity, collision detection, and pointer lock Block breaking and placement with visible targeting feedback A nine-slot hotbar with selectable block types Simple inventory, pause menu, settings, and responsive HUD Dynamic sunlight, shadows, fog, clouds, particles, water animation, and a day-night cycle Local save and load for player position and edited blocks A landing screen with Play, Continue, Settings, and About options
Visual direction: bright, stylized voxel diorama graphics with crisp cubic geometry, dense handcrafted details, soft cinematic lighting, ambient occlusion, clean shadows, colorful terrain, and a polished miniature-world feel. Use React, TypeScript, Vite, and React Three Fiber. Optimize rendering with instancing, chunk-based terrain generation, frustum culling, and lazy loading. Support desktop browsers and show a clear message on unsupported mobile devices. Deliver a complete runnable project with organized components, original placeholder assets generated in code where possible, setup commands, controls, and no missing implementation stubs.
Assistant
I will start by exploring the workspace to see the existing files, folders, and structure. I will use
list_filesto inspect the project layout.I need to see what libraries are installed in
package.jsonto determine whether we need to install@react-three/fiber,@react-three/drei,three, and Lucide icons (for clean UI icons) to build our voxel sandbox game. Let's readpackage.jsonfirst. I will useread_fileforpackage.json.I need to install
three,@react-three/fiber,@react-three/drei,@types/three, andlucide-reactfor beautiful UI icons. Let's install these packages first usinginstall_npm_packages. Let's install:three,@types/three,@react-three/fiber,@react-three/drei, andlucide-react. Note: We should install versions compatible with React 19. React 19 is used, so let's check or install compatible versions. Installing standard versions:three,@types/three,@react-three/fiber,@react-three/drei,lucide-react. Let's callinstall_npm_packages.Let's create a beautiful voxel game with rich mechanics. Let's design the layout and files of our game:
- Title and Customization in
index.html: Set the title to "VoxelCraft - Infinite Sandbox RPG". - Game Engine and Assets:
- We will write a fast and optimized voxel engine in custom TypeScript files.
- We need noise generation for procedural generation (Simplex/Perlin noise style, or a fast sine-wave fractional Brownian noise in code to avoid massive dependencies). Let's implement an efficient, deterministic noise generator in custom utility files.
- Let's support chunks, frustum culling, dynamic ambient occlusion, block textures generated via Canvas data URLs (or clean procedural textures created using CSS or Canvas and applied as canvas-textures, or sharp Canvas-drawn pixel patterns for Grass, Dirt, Stone, Sand, Oak Wood, Oak Leaves, Water, Glass, and Lava). This fits perfectly with the stylized, bright voxel diorama aesthetics!
- Hotbar with selectable blocks, inventory screen, pause menu, settings screen, day-night cycle, custom lighting, shadows, collision detection (allowing player to walk, jump, sprint, fall with gravity, break blocks, and place blocks).
- Local save & load of player positions and modified blocks.
- Beautiful visual instructions, controls overlay, creative/survival modes, seeds, and mobile warning overlay.
Let's design a high-quality noise function in
src/utils/noise.tsfirst. I will createsrc/utils/noise.tswith a reliable Simplex or Perlin noise approximation, plus fractal brownian motion (FBM) to give hills, caves, sand dunes, and deep oceans. This will make the landscape look extremely realistic and classic! Let's write this utility. I will explain this and callcreate_file.Now, let's build beautiful block textures dynamically using a canvas-generator. This prevents external asset loading issues and lets us generate crisp, pixelated, 16x16 or 32x32 retro 3D textures in code with beautiful ambient shadow effects, bevels, and vibrant voxel aesthetics (Grass, Dirt, Stone, Sand, Oak Wood, Oak Leaves, Glass, Water, Lava, and Coal Ore, Rose, Dandelion etc). Let's construct a dynamic canvas texture generator utility in
src/utils/textures.ts. It will return HTML Canvas elements or data URLs or custom color values, or we can build gorgeous material textures directly inside our game components using standard CanvasTextures or standard colorful PBR shaders! Let's writesrc/utils/textures.tswhich will define the block types, their colors, their icons, and draw beautiful block faces on canvas to generate Three.js canvas-textures! This is extremely powerful and fully responsive.Let's write
src/utils/textures.tsnow. I will usecreate_file.Let's write a file to handle the game's core physical states:
- Saving & loading from localStorage
- Custom block maps for modified blocks
- World seeds
- Player statistics (survival vs creative mode, speed, position, active blocks)
- Day/night timer settings
- Active sounds or visual options
Let's create a save-system and global configuration state inside
src/utils/saveSystem.ts. It will handle loading modified block coordinates(x, y, z)and custom user settings. Let's buildsrc/utils/saveSystem.ts. I will usecreate_file.Now, we need a wonderful first-person pointer-locked experience or drag-to-look system. We can implement a dual control system:
- Pointer Lock controls (desktop browser standard): Left click to break blocks, Right click to place blocks, WASD keys to run around, Space to jump, Shift to run/sprint.
- An elegant backup Touch / Drag-to-look control overlay when Pointer Lock is not enabled or on desktop browsers before clicking, as well as a fallback for those who prefer to click. This ensures maximum compatibility and comfort. Let's build a fully integrated controls hook or wrapper component to make first person exploration super smooth and natural!
Let's design the core 3D gameplay in a series of components:
src/components/TerrainChunk.tsx- efficiently renders a 16x16 chunk of blocks using optimized instancing or cached mesh geometries to guarantee 60fps!src/components/PlayerControls.tsx- manages key listeners, camera position, physics, collision detection with blocks, jumping, and interaction (block highlighting, breaking, placing).src/components/GameUI.tsx- manages the hotbar, crosshair, inventory screen, pause screen, settings, seed entry, mini-tutorial, dynamic clock showing the Day-Night cycle, and stats.src/components/VoxelWorld.tsx- manages the Canvas, lights, sky, clouds, particles, chunk storage, and loading.
Let's write a robust terrain generation manager
src/utils/terrain.tsthat will define:- Chunk size (16 width x 16 depth x 32 height)
- Generates block arrays based on noise and seeded random
- Generates caves (using dynamic conditions)
- Spawns trees (leaves and logs)
- Provides simple collision queries (e.g.
getBlockAt(x, y, z)) which is essential for real gravity & movement collision!
Let's build
src/utils/terrain.tsnow. This will make terrain and block management extremely clean and easy. I will usecreate_file.Ah, there was a small TS warning about unused imports in
src/utils/terrain.ts. Let's fix that minor issue right away by removing the unusedBlockTypeimport or using it, so that our build compiles flawlessly later! I will useedit_fileto remove the unusedBlockTypeimport insrc/utils/terrain.ts. Let's do it now.Awesome! Now, let's create a chunk renderer file:
src/components/TerrainChunk.tsx. This component will render a chunk's blocks using Three.js instanced meshes or grouped mesh elements. To maintain ultra-high performance and quick loading, instanced meshes are absolutely ideal! Wait! We can render blocks in a chunk using a singleinstancedMeshfor each unique block type, or even a singleTHREE.InstancedMeshwith dynamic colors. Let's create an elegant, robustInstancedMesh-based renderer that groups blocks of the same type together and renders them. This gives us gorgeous 60fps performance even with large draw distances, frustum culling, and beautiful diorama ambient shadows. Let's designsrc/components/TerrainChunk.tsxto:- Take chunk coordinates
cxandcz - Load blocks from the world terrain manager
- Query local decorations
- Combine everything into high-performance
InstancedMeshnodes - Exclude invisible internal blocks (blocks surrounded on all 6 sides by other solid blocks) to optimize the face rendering count! This is a classic voxel engine optimization trick that keeps rendering ultra-fast!
Let's write
src/components/TerrainChunk.tsxnow. I will explain this and callcreate_file.Ah, TypeScript's R3F definitions sometimes conflict with standard JSX or TS setup if React 19 types are active. This is extremely common and very easy to solve! To resolve the JSX Intrinsic elements error, we can add a type definition or simple cast, or configure a local React declaration, OR simply import/use standard
@react-three/fibernative elements or cast our component, or use Three.js imperative code insideuseFrame/useEffect, OR simply extend/define standard types, or cast our JSX return with aas any. Usingas anyor extending standardJSX.IntrinsicElementsinside a global file completely solves this. Let's create or add JSX types in a localsrc/react-app-env.d.tsorsrc/vite-env.d.tsto make sure Vite compiles everything beautifully without any type complaints! Let's search ifvite-env.d.tsor similar exists, or simply create a robustsrc/global.d.tscontaining the React Three Fiber intrinsic element definitions. Let's see if we havesrc/main.tsxor similar. Let's createsrc/global.d.tsfirst. I will usecreate_file.Let's test if we still have any type issues or if that solves it. We can also simply use standard R3F imports or cast element types if TypeScript complains. To be 100% robust, let's create a beautiful player controller that supports pointer lock, collision detection (AABB), block target detection, building, and mining. Let's design a highly functional first person controller inside
src/components/PlayerControls.tsx. This component handles:- WASD + Sprint (Shift) + Jump (Space)
- Gravity (pulls the player down if they are not touching ground)
- Dynamic block collision detection! It queries the
terrainManager's blocks around the player's bounding box to prevent them from walking through solid walls or falling through blocks, and allowing them to step up or jump. - Reticle-targeted blocks (raycasting): It casts a ray from the camera position in the camera's direction to see which block the player is looking at (up to 5 blocks away).
- Draws a beautiful 3D outline (wireframe) around the targeted block to give excellent targeting feedback!
- Allows left click to break/delete the targeted block and right click to place the selected hotbar block on the adjacent side!
- Plays dynamic feedback (block particles, animations).
Let's design and create
src/components/PlayerControls.tsx. This file will be the core game driver. I will usecreate_fileto create it.Let's fix the minor TS warnings and errors in
src/components/PlayerControls.tsxwith simple fixes:- Remove unused variables
mouseandheight. - Cast
activeBlockasBlockType(since block indices are mapped properly inBLOCK_DEFS). Let's modifysrc/components/PlayerControls.tsxusingedit_file. I will write a precise modification.
Now let's replace the other two issues in
src/components/PlayerControls.tsx.- Line 169:
BLOCK_DEFS[activeBlock as any]-> Let's change this to cast it asBlockType. - Line 352:
const checkCollisionAt = (pos: THREE.Vector3, manager: WorldTerrainManager, radius: number, height: number): boolean => {-> Let's change this to ignore or omitheightor use it, or just delete the parameter. Let's apply these edits now usingedit_file. I will useedit_fileto fix these.
Ah, we need to import
BlockTypeinsidesrc/components/PlayerControls.tsx! Let's edit the file to importBlockTypeand use proper types. Let's see the imports at the top of the file:import { BLOCK_DEFS } from '../utils/textures';Let's change it to:import { BLOCK_DEFS, BlockType } from '../utils/textures';And fix the unusedheightvariable. Let's do this usingedit_file.Wonderful! Now, let's look at the remaining TS error in
src/components/PlayerControls.tsxfor line 353 (unusedheightvariable incheckCollisionAt). Let's edit the file to remove or useheightproperly, or just remove the unused declaration inside the function if it's not needed, or delete the parameter. Let's look at the function signature:const checkCollisionAt = (pos: THREE.Vector3, manager: WorldTerrainManager, radius: number, height: number): boolean => {Let's see where it is called and change it. I will useedit_fileto fix this.Let's update the definition of
checkCollisionAtto only acceptpos, manager, radiusand removeheight/playerHeightreferences. Let's do that right now. I will useedit_file.Excellent. Now, let's update the definition of
checkCollisionAtto take 3 parameters instead of 4:const checkCollisionAt = (pos: THREE.Vector3, manager: WorldTerrainManager, radius: number): boolean => {Let's edit the file. I will useedit_file.The types in
src/components/PlayerControls.tsxare now absolutely perfect! Now let's build the Voxel World environment component:src/components/VoxelWorld.tsx. This file will orchestrate:- The Canvas element with scene setup.
- Multiple
TerrainChunknodes based on rendering distance (e.g., render a grid of chunk files around the player's position, like -2 to +2, or -1 to +1 chunks). Let's load 9 chunks (a 3x3 grid around player) or 25 chunks (a 5x5 grid), which looks gorgeous and runs super smoothly! Let's choose a 5x5 chunk grid centered on the player's position, so they see a beautiful endless world with misty horizons. - Skybox, mist/fog, stylized moving clouds (using simple floating 3D plane meshes), and particles (blocks breaking!).
- Dynamic Day/Night cycle: The sun and moon orbits, modifying background fog colors and ambient lighting intensity! During the day, we have a bright blue sky, and at night, we transition to a beautiful starlit dark indigo sky.
- Sound effects: Simple synthesizer beep sound fallbacks using standard browser Web Audio API! Yes, this adds amazing gameplay immersion with block mining noises and steps without needing actual external mp3 assets! This is clean and highly professional.
Let's build
src/components/VoxelWorld.tsx. This is going to be incredibly exciting! I will usecreate_file.Let's fix the minor TS error in
src/components/VoxelWorld.tsxwhereuseEffectis imported but never used. I will useedit_file.Beautiful! Now, let's build the premium, highly stylized user interface overlay and HUD inside
src/components/GameUI.tsx. What shouldGameUIlook like?- Interactive HUD (Head-Up Display):
- Dynamic 9-slot Hotbar at the bottom. The hotbar lists customizable block types (like Grass, Wood, Stone, Sand, Leaves, Glass, Red Brick, Diamond Ore, Rose Flower). Users can press Keys 1-9 to select a slot or scroll to change blocks.
- Beautiful, glowing modern heart container icons for Health (survival mode).
- Hunger bar icons represented by little drumsticks.
- Level indicator bar (XP progress bar).
- Compass or Coordinates overlay (displaying X, Y, Z position).
- Time tracker: Displays dynamic hour/clock (sunrise, day, sunset, night) and current active biome.
- Reticle/Crosshair in the center of the screen with visual click instructions.
- Pause Menu Overlay:
- Resuming game, Saving World feedback, Game seed, Mode switcher (Survival <=> Creative).
- Audio feedback toggles, rendering distance choices, resetting blocks.
- Inventory Screen Overlay:
- Opens when the player presses 'E' or clicks the inventory button!
- Shows all 15 available blocks with rich details, hardness value, and descriptions! Clicking any block assigns it to the current selected hotbar slot.
- Settings Modal / View:
- Fog toggle, Day/Night speed, Render distance slider.
- About screen / Voxel Diorama manual:
- Beautiful explanation of voxel mechanics, controls table (WASD, mouse-look, click, E key, Space).
Let's build
src/components/GameUI.tsxnow. This is going to look outstanding with gorgeous modern Tailwind colors and animations. I will usecreate_file.Let's fix the minor TS error in
src/components/GameUI.tsxabout the unusedMusicimport. I will edit the file to remove the unused import. I will useedit_file.Now, we need to create a beautiful landing screen so that when users first open the page, they are greeted by a gorgeous, retro classic background, options to "Play New World", "Continue Previous Sandbox", "Settings", and "Credits & About". Let's design a high-fidelity retro design with standard voxel grids, animated block rotation or canvas animation, and crisp CSS borders. Let's create
src/components/LandingScreen.tsxfor this layout.Wait, we should build a breathtaking layout in
src/components/LandingScreen.tsxwith:- Crisp classic font styling
- Glowing, bevelled buttons
- A dynamic, seed configuration input field to let players customize their worlds!
- Dynamic day-night speed options
- Clear warning messages on unsupported mobile devices (with a button to start anyway for tablets/touch devices, which guarantees absolute accessibility).
- Beautiful layout displaying a retro grid design and block list!
Let's write
src/components/LandingScreen.tsxnow. I will usecreate_file.Let's edit
src/components/LandingScreen.tsxto remove the unusedUserCheckimport. I will useedit_file.Now, let's look at
src/App.tsxand see how to wire everything up perfectly. Let's see the current contents ofsrc/App.tsxfirst. I will useread_fileto view its template.Let's write a complete, beautiful application inside
src/App.tsx. What willAppmanage?- State to determine if we are currently on the landing screen or playing the game.
- State to load local progress using
loadGamefrom oursaveSystem. - Active hotbar selection state.
- Dynamic game ticker/loop to increment
dayTimeticks (for the day/night cycle) at a configurable pace (e.g. 1 tick per frame, or we can pause it when the user pauses). - High quality handlers to save, clear saves, reset, replace hotbar, and increment blocks broken count statistics.
- Implements nice CSS style transitions, custom pointer indicators, instructions, and responsive layout.
Let's write
src/App.tsxcompletely. This is the heart of our website. I will explain this and callcreate_fileto replace it with our magnificent implementation.Let's clean up the minor unused variable warnings in
src/App.tsx(namelyisPlaying,setIsPausedState, andautoSaveTimer). I will useedit_fileto remove them to make sure the app compiles with absolutely zero type warnings. Let's do this immediately.Let's edit the file once more to remove the unused
autoSaveTimerref fromsrc/App.tsx. I will useedit_file.Let's edit the file to remove the unused
useRefimport fromsrc/App.tsx. I will useedit_file.Let's check the title in
index.htmlto give it a custom brand representation. I will readindex.htmlfirst. I will useread_file.Let's edit
index.htmlto update the title to "VoxelCraft - Infinite 3D Voxel Sandbox Game" and apply beautiful styles. I will useedit_file.Let's build the project using the
build_projecttool to verify that Vite compiles the entire voxel game (including procedural noise generation, instanced terrain chunks, canvas-drawn pixel textures, player controls with horizontal & vertical bounding box collision detection, nine-slot hotbar HUD, day-night cycle light transitions, and local save/load states) with zero compilation or build errors.The project built with complete success and absolutely zero errors! This is spectacular!
Let's summarize the application we have created for the user. We created an infinite procedural 3D voxel sandbox game in React + TypeScript + Three.js (React Three Fiber) called VoxelCraft, featuring high-performance chunk rendering, dynamic lighting, customizable settings, and local storage retention.
Files built:
src/utils/noise.ts,src/utils/textures.ts,src/utils/saveSystem.ts,src/utils/terrain.ts,src/components/TerrainChunk.tsx,src/global.d.ts,src/components/PlayerControls.tsx,src/components/VoxelWorld.tsx,src/components/GameUI.tsx,src/components/LandingScreen.tsx,src/App.tsx,index.html- Title and Customization in