Using babylon.js make a 3d city generator, place our character on ground, provide full…
- User
Using babylon.js make a 3d city generator, place our character on ground, provide full code in one file (HTML + JS)
- Assistant
Using babylon.js make a 3d city generator, place our character on ground, provide full code in one file (HTML + JS)
Certainly! Below is a full HTML file containing the code for a simple 3D city generator using Babylon.js. This script creates a scene with procedurally generated buildings, places a character on the ground, and allows basic movement controls for the character.
You can copy the entire code into a file with an .html extension and open it in a web browser to see it in action.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Babylon.js 3D City Generator</title>
<!-- Include Babylon.js from CDN -->
<script src="https://cdn.babylonjs.com/babylon.js"></script>
<!-- Include Babylon.js GUI (optional) -->
<script src="https://cdn.babylonjs.com/gui/babylon.gui.min.js"></script>
<!-- Include Babylon.js Loaders (if needed for models) -->
<script src="https://cdn.babylonjs.com/loaders/babylonjs.loaders.min.js"></script>
<style>
html, body {
overflow: hidden;
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
#renderCanvas {
width: 100%;
height: 100%;
touch-action: none;
}
</style>
</head>
<body>
<canvas id="renderCanvas"></canvas> <!-- Canvas for Babylon.js rendering -->
<script>
// Get the canvas element
var canvas = document.getElementById("renderCanvas");
// Generate the Babylon.js engine
var engine = new BABYLON.Engine(canvas, true);
// Create the scene
var createScene = function () {
var scene = new BABYLON.Scene(engine);
// Add a camera to the scene and attach it to the canvas
var camera = new BABYLON.UniversalCamera("UniversalCamera", new BABYLON.Vector3(0, 5, -10), scene);
camera.setTarget(BABYLON.Vector3.Zero());
camera.attachControl(canvas, true);
// Add a hemispheric light to the scene
var light = new BABYLON.HemisphericLight("light", new BABYLON.Vector3(0, 1, 0), scene);
light.intensity = 0.7;
// Create the ground
var groundSize = 200;
var ground = BABYLON.MeshBuilder.CreateGround("ground", {width: groundSize, height: groundSize}, scene);
// Generate buildings
var buildingCount = 100;
var maxBuildingSize = 10;
for (var i = 0; i < buildingCount; i++) {
// Random dimensions and position
var width = 2 + Math.random() * maxBuildingSize;
var depth = 2 + Math.random() * maxBuildingSize;
var height = 5 + Math.random() * 50;
var x = (Math.random() - 0.5) * groundSize * 0.9;
var z = (Math.random() - 0.5) * groundSize * 0.9;
// Create building
var building = BABYLON.MeshBuilder.CreateBox("building" + i, {width: width, depth: depth, height: height}, scene);
building.position = new BABYLON.Vector3(x, height / 2, z);
// Apply a simple material
var buildingMaterial = new BABYLON.StandardMaterial("buildingMat" + i, scene);
buildingMaterial.diffuseColor = new BABYLON.Color3(Math.random(), Math.random(), Math.random());
building.material = buildingMaterial;
// Optional: Enable shadows (requires a shadow generator)
}
// Create a character (simple sphere for demonstration)
var character = BABYLON.MeshBuilder.CreateCapsule("character", {height: 2, radius: 0.5}, scene);
character.position = new BABYLON.Vector3(0, 1, 0);
// Character movement variables
var inputMap = {};
scene.actionManager = new BABYLON.ActionManager(scene);
scene.actionManager.registerAction(new BABYLON.ExecuteCodeAction(BABYLON.ActionManager.OnKeyDownTrigger, function(evt) {
inputMap[evt.sourceEvent.key] = evt.sourceEvent.type == "keydown";
}));
scene.actionManager.registerAction(new BABYLON.ExecuteCodeAction(BABYLON.ActionManager.OnKeyUpTrigger, function(evt) {
inputMap[evt.sourceEvent.key] = evt.sourceEvent.type == "keydown";
}));
// Main game loop
scene.onBeforeRenderObservable.add(() => {
var deltaTime = engine.getDeltaTime() / 1000; // in seconds
var speed = 5;
// Character movement
if (inputMap["w"] || inputMap["ArrowUp"]) {
character.moveWithCollisions(character.forward.scaleInPlace(speed * deltaTime));
}
if (inputMap["s"] || inputMap["ArrowDown"]) {
character.moveWithCollisions(character.forward.scaleInPlace(-speed * deltaTime));
}
if (inputMap["a"] || inputMap["ArrowLeft"]) {
character.rotation.y -= speed * deltaTime;
}
if (inputMap["d"] || inputMap["ArrowRight"]) {
character.rotation.y += speed * deltaTime;
}
// Camera follows character
camera.position = character.position.clone();
camera.position.y += 5; // Adjust camera height
camera.rotation = character.rotation.clone();
});
return scene;
};
var scene = createScene();
// Run the render loop
engine.runRenderLoop(function () {
scene.render();
});
// Resize the engine on window resize
window.addEventListener("resize", function () {
engine.resize();
});
</script>
</body>
</html>
Explanation of the Code:
HTML and Canvas Setup:
<canvas> element with the id="renderCanvas" is where Babylon.js will render the 3D scene.Including Babylon.js:
<head> section.Creating the Scene:
UniversalCamera is created for a first-person perspective.HemisphericLight provides basic scene illumination.Generating Buildings:
MeshBuilder.CreateBox) with random dimensions and a random color.Creating the Character:
(0, 1, 0).Character Movement:
actionManager handles key input for character movement.w, a, s, d keys or arrow keys.moveWithCollisions function to prevent the character from passing through buildings (though collision detection with buildings requires enabling physics and collision detections for buildings).Camera Follow:
Controls:
Feel free to customize the code further by adding textures, refining the character model, improving movement logic, or adding environmental effects.
Not yet included in a published release.