简体   繁体   中英

Three.js - Spawn an object every x seconds and move each object forward (along Z)

I am making an endless runner style game using Three.js. The basic set up of the scene and idea for the game is a long moving road with cars coming towards you that you have to dodge out of the way of. I am still at the early stages of creating this game, and so my first problem is that I need the hero character (who is dodging the cars) to seem like he is moving forwards, and at the same time have the cars seem like they are moving (faster) towards the hero character.

My thinking was to create road strip objects (the white lines in the middle of a road), and have them move towards the hero character, who is at (0, 0), at a certain speed.

I have successfully created a road strip object and positioned it at the very back of the road ( RoadStrip.mesh.position.z = -5000; ). Here is my code for that:

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 createRoadStrip() {

    new objectRoadStrip();
    RoadStrip.position.y = -72.5;
    RoadStrip.position.z = -5000;

    scene.add(RoadStrip);

}

In the render() function, which is the function that loops over every frame and is called last to make sure the camera and scene update every frame, I am able to successfully move this strip forwards along the z axis by 10 every time render() is called. I also added some code so that when the RoadStrip touches (0,0), it is removed from the scene. See this below:

function render(){

    // moves RoadStrip towards (0,0). When it reaches z = -150, remove that strip from the scene

    if (RoadStrip.position.z <= -150) {
        RoadStrip.position.z += 10;
    } else {
        scene.remove(RoadStrip);
    }

    renderer.render(scene, camera);
    requestAnimationFrame(render);
}

I have also added the following code to the init() function which creates a RoadStrip when the scene is created, and the continues to create a RoadStrip every 10 seconds (roughly every time the RoadStrip reaches (0,0).

createRoadStrip();
setInterval( function() {
    createRoadStrip();
}, 10000);

This is similar to the effect I'm going for, but read The Problem section below where I explain what I truly need.

The Problem

I need to spawn a RoadStrip every x amount of seconds (still to be decided once I get it working, but lets say 3 seconds for now) continuously. Each RoadStrip needs to move towards (0,0) with z += 10 independently. When a RoadStrip instance reaches (0,0), it should be removed from the scene, but other RoadStrips should continue to spawn regardless every 3 seconds at the original position ( z = -5000 ).

My Attempts / Solution Ideas

I've done a lot of reading on this, trawling through code from other people's endless runner games and reading through SO answers but nothing seems to have worked. Below are some of the things I have tried, or some things that I feel would work but I am not doing right/don't have a good understanding of:

  1. Idea: Instead of calling the createRoadStrip() function inside a setInterval , push a RoadStrip object to an array every 3 seconds, and then call that array and move the array along the z axis by += 10 .
  2. Possible solution help: I tried changing the setInterval to less than 2 seconds instead of 10 seconds. This caused the RoadStrip to move along the Z axis for 2 seconds as expected, but of course, after 2 seconds another RoadStrip was spawned, and so the first RoadStrip stopped moving along the Z axis, and the new one did instead (for 2 seconds as well) and this process repeated infinitely. This is so close to what I need, but I need each RoadStrip to continue moving, and be remove from the scene when it reaches (0,0)

Thanks for taking the time to read my Question, I look forward to your solutions!

Examples of similar style games: First , Second .

Thanks to @prisoner849 and his link to this thread, I managed to find the solution to the problem, and so I am writing an answer here for anyone who comes across this with the same problem in the future!

I read through the thread and found a link to this JSFiddle , that includes a successful animation similar to the one I was trying to achieve, and I would highly suggest studying the code of that JSFiddle to fully understand how to create an endless runner effect.

Here is a detailed explanation of how to do this:

Instead of infinitely creating objects and have them animate forwards until they reach the end point and disappear (like I originally thought was the right solution), you have to create an array of objects and animate that instead.

Here is my code for doing this:

var roadStripArray = []

function objectRoadStrip() {

    for (var i = 0; i < 100; i++) {
        geomRoadStrip = new THREE.BoxGeometry(20, 11, 500);
        matRoadStrip = new THREE.MeshPhongMaterial({color: Colors.white});

        RoadStrip = new THREE.Mesh(geomRoadStrip, matRoadStrip);

        RoadStrip.position.set(0, -72.5, -150 - i * 1250);
        RoadStrip.receiveShadow = true;

        scene.add(RoadStrip);
        roadStripArray.push(RoadStrip);
    }

}

The for loop has the code i < 100 as my road is quite long and therefore needs a lot of strips

This code:

RoadStrip.position.set(0, -72.5, 0 - i * 1250);

sets the position of each strip to be different from each other, and the number 1250 is the distance between each strip

After creating the objects, you must animate them in the render() function. You have to set them to move along the Z axis, and then create an if statement that says "if any strip reaches the end point (where you want it to disappear), reset it's position back to the start (ie the start of the road for me). This means you are constantly looping through your array of objects, and therefore don't infinitely create them.

Here is the code that animates the strips:

// loop that runs every frame to render scene and camera
var clock = new THREE.Clock();
var time = 0;
var delta = 0;
var direction = new THREE.Vector3(0, 0, 1);
var speed = 2000; // units a second - 2 seconds

function render(){
    requestAnimationFrame(render);

    delta = clock.getDelta();
    time += delta;

    roadStripArray.forEach(function(RoadStrip){
        RoadStrip.position.addScaledVector(direction, speed * delta);
        if (RoadStrip.position.z >= 10000) {
            RoadStrip.position.z = -10000;
        } else {
        }
    });
    renderer.render(scene, camera);
}

The code that moves each strip is:

RoadStrip.position.addScaledVector(direction, speed * delta);

You can read more about .addScaledVector here , but essentially this is the code that animates the strip.

The if statement then checks if the strip touches 10000 (ie the end of the road), and if it does, sets the position of that strip to -10000 . That strip then moves back towards the end point along the Z axis.

We wrap this all in a forEach function to loop through each RoadStrip in the array and animate them all in the same way. We need to animate them individually so that we can detect when one of them reaches the end of the road.

Thanks, hope this helps!

Usually this kind of scenario is best handled with some kind of particle-system like approach: you don't insert/remove objects continuously to the scene but create a set of objects during initialization, let's say the player can only see 10 road stripes at a time, and your game logic is always moving those 10 stripes, updating positions as needed, once one strip goes out of the field of view, it is recycled at the begining and so on. I don't think you will find a canned solution that does exactly what you are looking for, you would need to come up with the update logic that suits best your game.

I have an example of custom particle system there . Once a particle is getting out of scope, it is made available for the system when it needs to emit a new particle. The number of particle in the pool is always constant and can be defined by the user here just for testing purpose. A similar approach can be used to manipulate your infinite stripes. The repo for that code is available at https://github.com/leefsmp/Particle-System but you can find many other particle system implementations out there, this one is a bit specific to my needs.

Hope that helps.

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM