Objects spawning at the horizon takes too long to reach player.

I am new to programming and Unity and am making a simple car driving game.
I want one of the unique things about the game to be that the player should see the road and cars all the way to the horizon. I include an image just to give you an idea.

However, if I spawn the cars (randomized) coming towards the player, all the way at the horizon, it would take forever for those cars to reach the player.

Can/should I make it so that everything has been “fast forwarded” so that the cars has already reached the player by the time one starts playing?

Or how do I solve this?

Depends on the game.

You could shorten the horizon distance in various ways:

  • curve the ground?
  • make a fog?
  • clip it off into blackness / sky?
  • something else?

You could even scale cars velocities up the further away they are.

Either way, if you’re out of ideas, go check out tutorials for games that have similar spawn situations.

Tutorials and example code are great, but keep this in mind to maximize your success and minimize your frustration:

How to do tutorials properly, two (2) simple steps to success:

Step 1. Follow the tutorial and do every single step of the tutorial 100% precisely the way it is shown. Even the slightest deviation (even a single character!) generally ends in disaster. That’s how software engineering works. Every step must be taken, every single letter must be spelled, capitalized, punctuated and spaced (or not spaced) properly, literally NOTHING can be omitted or skipped.
Fortunately this is the easiest part to get right: Be a robot. Don’t make any mistakes.
BE PERFECT IN EVERYTHING YOU DO HERE!!

If you get any errors, learn how to read the error code and fix your error. Google is your friend here. Do NOT continue until you fix your error. Your error will probably be somewhere near the parenthesis numbers (line and character position) in the file. It is almost CERTAINLY your typo causing the error, so look again and fix it.

Step 2. Go back and work through every part of the tutorial again, and this time explain it to your doggie. See how I am doing that in my avatar picture? If you have no dog, explain it to your house plant. If you are unable to explain any part of it, STOP. DO NOT PROCEED. Now go learn how that part works. Read the documentation on the functions involved. Go back to the tutorial and try to figure out WHY they did that. This is the part that takes a LOT of time when you are new. It might take days or weeks to work through a single 5-minute tutorial. Stick with it. You will learn.

Step 2 is the part everybody seems to miss. Without Step 2 you are simply a code-typing monkey and outside of the specific tutorial you did, you will be completely lost. If you want to learn, you MUST do Step 2.

Of course, all this presupposes no errors in the tutorial. For certain tutorial makers (like Unity, Brackeys, Imphenzia, Sebastian Lague) this is usually the case. For some other less-well-known content creators, this is less true. Read the comments on the video: did anyone have issues like you did? If there’s an error, you will NEVER be the first guy to find it.

Beyond that, Step 3, 4, 5 and 6 become easy because you already understand!

Finally, when you have errors, don’t post here… just go fix your errors! Here’s how:

Remember: NOBODY here memorizes error codes. That’s not a thing. The error code is absolutely the least useful part of the error. It serves no purpose at all. Forget the error code. Put it out of your mind.

The complete error message contains everything you need to know to fix the error yourself.

The important parts of the error message are:

  • the description of the error itself (google this; you are NEVER the first one!)
  • the file it occurred in (critical!)
  • the line number and character position (the two numbers in parentheses)
  • also possibly useful is the stack trace (all the lines of text in the lower console window)

Always start with the FIRST error in the console window, as sometimes that error causes or compounds some or all of the subsequent errors. Often the error will be immediately prior to the indicated line, so make sure to check there as well.

Look in the documentation. Every API you attempt to use is probably documented somewhere. Are you using it correctly? Are you spelling it correctly?

All of that information is in the actual error message and you must pay attention to it. Learn how to identify it instantly so you don’t have to stop your progress and fiddle around with the forum.

1 Like

Thanks, but the long queue of cars towards the horizon is a big part of the game, so I don’t want to shorten or obscure it.
And I’ve already searched for solutions online, but this is not a case that is very easy to google.

Scaling up the velocities? Hmm… that may actually work if I make the spawning and moving go extremely fast within the very first second of the game.
How would I make this happen in code?

Oh, it’s you again. :smile:

Let me hit you with a hot idea, how about we pool a ton of cars outside the camera’s view, like a big comfy car pile. You would need to load a few more than required to fill that rollercoaster of a freeway.

Then, as the level loads, position enough of them on the road all the way to the horizon, so that the ones closest to your car are only about 100 meters away as the game starts and remember what I told you in your other thread to prevent complete barriers.

From the start you could position them so that those farther away are already positioned in a way that ups difficulty.

When the cars move out of view, we toss 'em back in the pool. And don’t worry about repetition, we’ll just keep grabbing cars from the pool and plopping them near the horizon, the players won’t be any wiser.

1 Like

Yikes! It’s probably a brilliant idea, but I’m struggling to understand this :point_up: :face_with_spiral_eyes:

But how about giving my spawner super-speed for the first few seconds or frames from starting the game?
Something like this:

“IF this is the very start of the game, THEN multiply spawn speed by 10 000?”

The game will actually start in a top down camera view, so the player wouldn’t notice the cars racing towards him from the other side of the continent in super-speed for the first few seconds. :smile:

Let me see if I can get all the threads you’re opening into a concise picture: You want to keep the cars invisible for a few frames, have them move at lightspeed from the horizon to a position close to the player and then set their visibility to true? You know you’re still gonna have to do it for a lot of cars or else your other cars may seem to appear out of thin air. There’s of course hacky wacky ways to do this, but it’s neither elegant, nor efficient. You should really think about better ways to do this, even if it seems difficult at first.

  • The first 30 seconds or so, the game will actually be played in “Top Down” perspective, so the horizon won’t be in the camera view.
  • My idea is to spawn 5000 meters worth of cars (they will only be boxes even in the finished game!) and move them at light-speed towards the player within the first few seconds of my game, but the player wouldn’t see them since that would all be happening outside of the current camera view.
  • I totally understand that my solution will not be elegant or efficient in any sense, but at my level I’d rather go with something “bulky” if it is easier for me to understand and implement. :wink:
    The spawn function I understand mostly, and I might be able to speed it up. But how to spawn the cars [which should be moving at different speeds] so that they never create an impassable “wall” seems like wizard-level to me.:face_with_spiral_eyes:

If that seems like wizard level to you, wait until you first hear about the term “serializing” - but I digress. As to your approach:

Here’s a high-level approach, but it’s only one of many possibilities:

Before you spawn a car, spawn a collider on one of the other two lanes in an area that should be free. once you spawned the collider, check if it is intersecting with any cars. if it is, do the same for the other possible lane. if that one is also blocked, you know, you’re on the only free lane and you shouldn’t spawn your car there - else happy spawning.

1 Like

Oh, that’s clever!
For what it’s worth I got another suggestion from Discord:

"A simple way to do this is to reverse the process. You generate a valid path for the player and after that you fill in the gaps randomly outside the path. That way 100% of the time you have at least 1 path the player can take.

It very very doable and is a classic way to do this. you need to break your spawning in sections. The end of the previous section is the start of the next one. Inside a section to generate a path you just give it random directions forward, like up, left, left, up, right, up, right (making sure it stays inside the limits). Then you spawn stuff where the path isn’t."

But your suggestion seems slightly less complex for me to wrap my head around.
Anyways… I’ll start by seeing if I can make the cars spawn and speed up during the first few seconds.

You’re right, my suggestion is less complex, because it doesn’t involve any pathfinding, but that Discord suggestion you got, would frankly be better, because it leaves less room for failure due to inaccuracies.

1 Like

Since the first 30 seconds or so will be played in Top Down view, someone gave me the simple but brilliant idea to simply move the Spawn Position further along the road on the Z-axis.
In other words, start spawning near and then continually spawning further away until the Spawn Position reaches the horizon (5 000 meters) on the Z-axis.

This seems to work well in my experiment on a smaller scale! But now I have a little issue with the first six or so cars being spawned in a cluster at the beginning.

How do I fix this?

This is my current code in my SpawnManager script:

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

public class SpawnManager : MonoBehaviour
{
    public GameObject[] obstaclePrefabs;
    private float[] spawnPosX = { -2, 0, 2 };
    private float spawnPosZ = 10f;
    private float spawnInterval = 0.07f;
    public float resetTime = 0;

    void Start()
    {
      //  InvokeRepeating("SpawnRandomObstacle", startDelay, spawnInterval);
    }

    void Update()
    {

        if (spawnPosZ < 100) { spawnPosZ += 1; }
        if (spawnPosZ >= 100) { spawnInterval = 1f; }

        resetTime += Time.deltaTime;
        while (resetTime > spawnInterval )
        {
            SpawnRandomObstacle();
            resetTime -= spawnInterval;
        }
    }

    void SpawnRandomObstacle()
    {
        int obstacleIndex = Random.Range(0, obstaclePrefabs.Length);
        int spawnPosIndex = Random.Range(0, spawnPosX.Length);

        Vector3 spawnPos = new Vector3(spawnPosX[spawnPosIndex], 0.5f, spawnPosZ);

        Instantiate(obstaclePrefabs[obstacleIndex], spawnPos,
            obstaclePrefabs[obstacleIndex].transform.rotation);
    }
}

And this is my code controlling the speed of the meeting cars:

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

public class Obstacles_Movement : MonoBehaviour
{
    private float speedTraffic = 5;
    private int destroyZ = -15;

    void Start()
    {
       
    }

    void Update()
    {
        if (tag == "Traffic")
        {
            transform.Translate(0, 0, -speedTraffic * Time.deltaTime );
        }

        if (transform.position.z < destroyZ)
        {
            Destroy(gameObject);
        }

    }
}

By debugging! Here is how you can begin your exciting new debugging adventure:

You must find a way to get the information you need in order to reason about what the problem is.

Once you understand what the problem is, you may begin to reason about a solution to the problem.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as Debug.Log("Problem!",this);

If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer or iOS: How To - Capturing Device Logs on iOS or this answer for Android: How To - Capturing Device Logs on Android

If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

When in doubt, print it out!™

Note: the print() function is an alias for Debug.Log() provided by the MonoBehaviour class.

1 Like

I noticed that when I started the game in “paused” mode and stepped forward frame by frame, the clustering error didn’t occur. I tried experimenting by changing: resetTime += Time.deltaTime And when I changed it to: resetTime += Time.fixedDeltaTime; …the cluster went away!

I tried to read up on fixedDeltaTime, but I don’t understand it. Are there any drawbacks by using it compared to deltaTime?

deltaTime is like your boss - it tells you how much time has passed since the last time you checked (last frame), and you just have to deal with it.

fixedDeltaTime is like a reliable old friend - it always gives you the same amount of time, no matter what’s going on around you. It’s not meant to aggregate time with it in the Update method, because it would yield wrong results. It’s meant to be used in FixedUpdate().

float t1;
float t2;

void FixedUpdate()
{
    t1 += Time.fixedDeltaTime;
}

void Update()
{
    t2 += Time.deltaTime;
    Debug.Log(t2-t1); // <-- Should stay awfully close to zero
}
2 Likes

I appreciate your humor and the analogies :smile:

For me it generates around 0.003… to around 0.014…
But I have no idea what to do with that information :stuck_out_tongue:

So, anyway… I get the impression that you’re saying I shouldn’t really be using Time.fixedDeltaTime to solve the clustering. Then I may have to resort to plan B… and simply delete the first 5 objects generated! :smile:
As you can tell I’m currently at the level of brute forcing my projects to completion rather than doing so elegantly :smile:

But I still have the crux of preventing the cars from ending up in an impassable formation:
https://discussions.unity.com/t/911122
:face_with_spiral_eyes:

The fundamental problem here is you have a while loop to spawn ALL the things to the horizon…

… and yet… you only update SpawnPosZ from OUTSIDE of that while loop.

So position changes and now you spawn 7 guys… all at that same position.

Next update position changes and you spawn… I dunno, how many? Go find out!

This is why I suggested debugging. One or two strategically-placed Debug.Log() statements would have revealed this to you about 11 messages ago.

1 Like

Thanks, but you’re expecting me to run before I can walk.
I wouldn’t know where to place those Debug-thingies, and even if I did I would then just stare blankly at a bunch of text in the Console window not knowing what to make of it.
At this point I’m mostly helped by straight answers. And I do pick up a bits of knowledge also by simply trying to make the “straight answers” function with my code.

People not within view or control of your computer can only give you so much.

My post gives you techniques to get “straight answers” out of your own codebase.

I urge you to apply yourself to understanding precisely WHAT your program is doing, simply because you’re not going to get very far without being able to analyze your running program.

Good luck!

I’m sorry, but being spoonfed information bit by bit (much of which has to be guessed) won’t get you very far. It seems to me, that you problem isn’t so much your logic, but a lack of understanding of C# or maybe even coding in general.

Take this as a well-intentioned advice: you really should go back to a thorough and detailed C# beginner’s course from A to Z and properly learn the language and its’ aspects from the ground up. Right now you’re lacking basic understanding of loops, keywords, attributes, events and probably more. I truly, honestly don’t mean to belittle you, but if you’re serious about working with Unity you’ll eventually run into things like polymorphism, inheritance chains, reflection and serialization, and without the understanding of the very basics, those will remain hieroglyphs to you forever.

I constantly go through courses in parallel with this project. This project actually started as a task for a “personal project” in one of the courses, and now I have a great idea which I want to bring to mobile devices. I’m a computer artist/illustrator, so the design will look very different from the mockup graphics you see in my screenshots.
I actually learn a lot from being “spoon fed”, in piecing it all together etc. Rather than spending days or weeks trying to solve one single issue on my own, which would likely lead me to give up programming.
But I understand if it’s tedious on your end. So, do you know where I can hire someone to aid me with the trickier parts of the code needed for my game, like “path finding” for example?