Sure! Below is an HTML file that uses Babylon.js to create a simple scene with grassy ground. The player can walk around using the keyboard, and the grass will sway when the player steps on it.
For simplicity, we'll simulate the grass as a plane with a shader material that animates based on proximity to the player.
Here's the complete code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Babylon.js Grass Sway Example</title>
<!-- Include the Babylon.js CDN -->
<script src="https://cdn.babylonjs.com/babylon.js"></script>
<!-- For keyboard inputs -->
<script src="https://cdn.babylonjs.com/gui/babylon.gui.min.js"></script>
<!-- For advanced textures -->
<script src="https://preview.babylonjs.com/babylonjs.loaders.min.js"></script>
<style>
html, body {
overflow: hidden;
width: 100%;
height: 100%;
margin: 0;
}
#renderCanvas {
width: 100%;
height: 100%;
touch-action: none;
}
</style>
</head>
<body>
<canvas id="renderCanvas"></canvas>
<script>
// Get the canvas element
const canvas = document.getElementById('renderCanvas');
// Generate the Babylon.js 3D engine
const engine = new BABYLON.Engine(canvas, true);
// Create the scene
const createScene = function () {
// Create a new scene
const scene = new BABYLON.Scene(engine);
// Enable physics (optional, can be used for more advanced interactions)
// scene.enablePhysics();
// Create a FreeCamera, and set its position
const camera = new BABYLON.UniversalCamera("UniversalCamera", new BABYLON.Vector3(0, 2, -10), scene);
camera.attachControl(canvas, true);
// Enable camera keyboard controls
camera.keysUp.push(87); // W
camera.keysDown.push(83); // S
camera.keysLeft.push(65); // A
camera.keysRight.push(68); // D
// Create a hemispheric light
const light = new BABYLON.HemisphericLight('light1', new BABYLON.Vector3(0, 1, 0), scene);
light.intensity = 0.7;
// Create the ground (grass)
const ground = BABYLON.Mesh.CreateGround('ground1', 50, 50, 1, scene);
// Create a shader material for the grass
const grassMaterial = new BABYLON.ShaderMaterial("grass", scene, {
vertex: "grass",
fragment: "grass",
},
{
attributes: ["position", "normal", "uv"],
uniforms: ["world", "worldView", "worldViewProjection", "view", "projection", "time", "playerPosition"]
});
// Load grass texture
const grassTexture = new BABYLON.Texture("https://i.imgur.com/fNRzaJX.jpg", scene);
grassMaterial.setTexture("grassTexture", grassTexture);
// Set initial time
grassMaterial.setFloat("time", 0);
// Apply the material to the ground
ground.material = grassMaterial;
// Keep track of time
let time = 0;
// Register a render loop to animate the scene
scene.registerBeforeRender(function () {
time += scene.getEngine().getDeltaTime() * 0.001;
grassMaterial.setFloat("time", time);
grassMaterial.setVector3("playerPosition", camera.position);
});
// Grass vertex shader
BABYLON.Effect.ShadersStore["grassVertexShader"] = `
precision highp float;
// Attributes
attribute vec3 position;
attribute vec3 normal;
attribute vec2 uv;
// Uniforms
uniform mat4 worldViewProjection;
uniform float time;
uniform vec3 playerPosition;
// Varyings
varying vec2 vUV;
void main(void) {
vec3 p = position;
float distanceFromPlayer = length(playerPosition.xz - position.xz);
// Sway effect based on player's proximity
float sway = exp(-distanceFromPlayer * 2.0) * sin(time * 5.0 - distanceFromPlayer * 10.0) * 0.5;
p.y += sway;
gl_Position = worldViewProjection * vec4(p, 1.0);
vUV = uv;
}
`;
// Grass fragment shader
BABYLON.Effect.ShadersStore["grassFragmentShader"] = `
precision highp float;
varying vec2 vUV;
uniform sampler2D grassTexture;
void main(void) {
vec4 color = texture2D(grassTexture, vUV);
gl_FragColor = color;
}
`;
return scene;
};
const scene = createScene();
// Run the render loop
engine.runRenderLoop(function () {
scene.render();
});
// Resize the engine when the window is resized
window.addEventListener('resize', function () {
engine.resize();
});
</script>
</body>
</html>
Explanation:
-
HTML Structure:
- We include the necessary Babylon.js scripts via CDN.
- The
<canvas> element with id="renderCanvas" is where the scene will be rendered.
- Styles are set to make the canvas fill the entire window.
-
Scene Setup:
- We create a Babylon.js engine and a scene.
- Camera:
- A
UniversalCamera is used to allow movement similar to a first-person controller.
- We attach keyboard controls (
WASD) for movement.
- Light:
- A hemispheric light illuminates the scene.
- Ground (Grass):
- We create a ground mesh using
BABYLON.Mesh.CreateGround.
- A custom shader material (
ShaderMaterial) is applied to the ground to simulate the grass swaying effect.
-
Shader Material:
- Vertex Shader:
- Calculates the sway effect based on distance from the player.
- Positions of vertices are adjusted in the Y-axis to simulate swaying.
- Fragment Shader:
- Applies a grass texture to the ground.
- Uniforms and Attributes:
- We pass in the
time and playerPosition uniforms to animate the grass.
- Attributes like
position, normal, and uv are used in the shaders.
-
Animation Loop:
- The
registerBeforeRender function updates the time uniform and the playerPosition uniform before each frame.
- This makes the grass react in real-time to the player's movements.
Notes:
- Grass Texture:
- A sample grass texture is loaded from an online source. You can replace
"https://i.imgur.com/fNRzaJX.jpg" with the URL of any grass texture you prefer.
- Sway Effect:
- The sway effect is achieved by modifying the Y-position of the ground's vertices in the vertex shader.
- The sway amplitude decreases with distance from the player, creating the effect of grass reacting to the player's presence.
- Controls:
- Use
W, A, S, D keys to move around the scene.
- Improvements:
- For a more realistic effect, consider using a more detailed grass mesh or particle systems.
- Implement collision detection and physics for more interaction between the player and the environment.
How to Run:
- Save the code above into a file with an
.html extension, e.g., grass.html.
- Open the file in a modern web browser (like Chrome or Firefox).
- The scene should load, and you can start moving the camera using the keyboard.
References:
Feel free to ask if you have any questions or need further assistance!