Troll1011
Troll1011

Reputation: 3

How can I make it so that obstacles spawn based on how far the player has moved?

I have a problem when spawning obstacles. My character is a rocket which accelerates indefinitely and if the obstacles spawn at a fixed rate, the rocket will surpass the rate of the obstacles spawning. I do not want to spawn many objects at once. The rocket moves diagonally so I made some piece of code which shows that if the rocket's x position is a multiple of five it would spawn an obstacle. However it never gets to a multiple of five because it's x position has decimals.

This is my code so far.

using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;

public class TriangleSpawner : MonoBehaviour
{
    public GameObject Triangles;
    public float Spacing = 4f;
    Vector2 location;

    void Update()
    {
        location = new Vector2(transform.position.x, transform.position.y);
        if (location.x % 5 == 0)
        {
            Spacing = Spacing + 6.5f;
            GameObject newTriangle = Instantiate(Triangles);
            newTriangle.transform.position = transform.position + new Vector3(Spacing, Random.Range(-4, 3), 0);
        }
    }
}

How can I change this code so it can spawn based on the rocket's position so it never gets too slow?

Upvotes: 0

Views: 150

Answers (1)

Yuri Nudelman
Yuri Nudelman

Reputation: 2943

You can for example remember the last position when an object was spawned, then see on each frame whether or not the player has moved far enough from it to spawn another one. Example:

private float lastSpawnX;

void Start()
{
    lastSpawnX = transform.position.x;
}

void Update()
{
    if (Mathf.Abs(transform.position.x - lastSpawnX) >= 5)
    {
        lastSpawnX = transform.position.x;
        // Spawn here, do what you have to
    }
}

You should also consider what you are planning to do when the game becomes too fast, i.e you move more than 5 units in one frame. Normally you would always want some upper limit on how fast it can be.

Upvotes: 2

Related Questions