I am currently developing a Three.js endless runner game where the player controls a character dodging cars on a moving road. At this early stage of development, my main challenge is to make the hero character appear to be moving forward while creating the illusion that the cars are approaching the hero at a faster speed.
To achieve this effect, I decided to implement road strip objects that move towards the hero character's position (0, 0) at a specified velocity.
After successfully creating a road strip object and placing it at the back of the road (
RoadStrip.mesh.position.z = -5000;
), here is the code snippet:
// Code for creating a road strip object
var objectRoadStrip = function() {
this.mesh = new THREE.Object3D();
this.mesh.name = "roadStrip";
geomRoadStrip = new THREE.BoxGeometry(20, 11, 300);
matRoadStrip = new THREE.MeshPhongMaterial({color: Colors.white});
RoadStrip = new THREE.Mesh(geomRoadStrip, matRoadStrip);
RoadStrip.name = 'roadStripName';
this.mesh.add(RoadStrip);
}
// Function to create a road strip
function createRoadStrip() {
new objectRoadStrip();
RoadStrip.position.y = -72.5;
RoadStrip.position.z = -5000;
scene.add(RoadStrip);
}
In the render()
function, I can animate the road strip to move towards (0, 0) on the z
axis by 10
units on each frame. Additionally, the road strip is removed from the scene once it reaches the hero character's position:
// Road strip animation in the render function
function render(){
if (RoadStrip.position.z <= -150) {
RoadStrip.position.z += 10;
} else {
scene.remove(RoadStrip);
}
renderer.render(scene, camera);
requestAnimationFrame(render);
}
Furthermore, I have integrated the creation of a new road strip object every 10 seconds in the init()
function:
// Creating a new road strip every 10 seconds
createRoadStrip();
setInterval( function() {
createRoadStrip();
}, 10000);
While this approach simulates the desired effect, read the following section where I outline the actual problem and possible solutions.
The Problem
I aim to continuously spawn road strip objects every x seconds (e.g., 3 seconds) independently moving towards (0, 0) along the z
axis. Once a road strip reaches (0, 0), it should be removed, while new road strips continue to spawn at the original position (z = -5000
).
My Attempts / Solution Ideas
In exploring potential solutions, I considered pushing road strip objects to an array every x seconds and updating their positions in the array to achieve continuous movement. However, implementing this idea has proven to be challenging.
- Idea: Instead of using
setInterval
, push road strip objects to an array at intervals and update their positions. - Possible solution help: Adjusting the interval for creating new road strips caused inconsistent movement patterns. Each road strip stops moving once a new one is created, disrupting the continuous motion effect.
If you have insights or solutions to help overcome this challenge, I would greatly appreciate your input. Thank you!