Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Any tips for optimizing? #23

Closed
highwaywarrior0 opened this issue Nov 17, 2021 · 12 comments
Closed

Any tips for optimizing? #23

highwaywarrior0 opened this issue Nov 17, 2021 · 12 comments

Comments

@highwaywarrior0
Copy link

This isn't really an issue, the traffic system works perfectly but the maps I'm using it on are huge, so it has very bad performance.

Do you have any suggestions for optimizing the system on big maps? I'm new to the scripting stuff on Unity so I don't know much.

@highwaywarrior0 highwaywarrior0 changed the title Any tips for optimizing Any tips for optimizing? Nov 17, 2021
@mchrbn
Copy link
Owner

mchrbn commented Nov 17, 2021

If your camera does not have an overview of the whole map, you could try to deactivate the cars when they are not visible by your main camera.

I never used it but maybe these functions could help:

https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnBecameVisible.html
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnBecameInvisible.html

So inside OnBecameVisible you can set the object to .SetActive(true) and OnBecameInvisible to .SetActive(false)

@highwaywarrior0
Copy link
Author

But if i deactivate a car it stops and loses all the motion, and when i activate it again it just starts driving from 0 km/h.
Is it possible to keep the motion when deactivating cars?

@highwaywarrior0
Copy link
Author

Just found out I can't use those OnBecameVisible/OnBecameInvisible stuff for settings the activeness of an object since when some object gets deactivated it can never get activated again by OnBecameVisible.

Well I could use them for enabling/disabling renderers but i think Unity already stops rendering objects when they are not visible on camera.
I could use it for collisions or Traffic System scripts on cars too but stuff becomes broken and weird if i do that.

@highwaywarrior0
Copy link
Author

highwaywarrior0 commented Nov 17, 2021

I think what i need at the moment is being able to spawn cars with some motion, I mean not from 0 km/h. I want them to spawn with a specific velocity.

So i can just spawn them anywhere, like in the middle of the road when player comes close to spawnpoints, and destroy the cars that are far from player.

I think that will be good for performance, do you know how can i do it?

@mchrbn
Copy link
Owner

mchrbn commented Nov 18, 2021

Yes that would be a good solution as well!
You can increase the "Max Torque" parameter of your vehicles to make them reach faster their speed limit - works for you?

@highwaywarrior0
Copy link
Author

Well i increased it a lot, but the difference is very small
Increasing the speed limit seems like it doesn't affect much too.
Decreasing these values definitely make the car go slower but increasing them wont do much.
There isnt a visible difference between 3000000 Min/Max Speed and 300 Min/Max Speed

Also what does stuff like Steering Lerp and Brake Torque do?

@highwaywarrior0
Copy link
Author

highwaywarrior0 commented Nov 18, 2021

Turns out that these were happening because of my Rigidbody Drag settings,
I increased them a bit to keep cars more stable, otherwise they don't have enough grip when turning and everything gets wonky.
Well changing these values makes cars faster but i don't want the cars to be faster, just need them to spawn with a certain speed

And i don't think there is any option other than increasing the drag values, these cars just cant turn when they are going fast

@highwaywarrior0
Copy link
Author

I found a way to spawn the car with velocity, and implemented object pooling.
Now what i need is automatically putting the spawnpoints on the road, at the moment im trying to find a way to put spawners on Traffic System Gizmo arrows.

@mchrbn
Copy link
Owner

mchrbn commented Nov 20, 2021

Glad you found a way to spawn the car with velocity - just curious, how did you do it?

To spawn cars on your waypoint system you can do as below. Basically, you get all the segments and then for each segment, iterate through all the waypoints' positions. Then it's easy, you can just calculate a new point (where you will spawn you car) which will be in between waypoint X and waypoint Y at a certain distance D from waypoint X.

using UnityEngine;
using TrafficSimulation;

public class SpawnOnLine : MonoBehaviour
{
    void Start()
    {
        //Get all segments
        Segment[] ss = GameObject.FindObjectsOfType<Segment>();
        foreach(Segment s in ss){
            for(int i=0; i<s.waypoints.Count - 1; i++){
                //Here put the distance that the point should be from waypoint-i
                float distance = 3f;

                //Vector from i to i+1 and factor with the distance
                Vector3 v = s.waypoints[i+1].transform.position  - s.waypoints[i].transform.position;
                float f = distance / v.magnitude;
                v *= f;
                
                //Compute new point in between i and i+1 at a certain distance from i
                Vector3 np = new Vector3(s.waypoints[i].transform.position.x + v.x, s.waypoints[i].transform.position.y + v.y, s.waypoints[i].transform.position.z + v.z);

                //Spawn cube for debug purpose at the location
                GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
                cube.transform.position = np;
            }
        }
    }
}

@highwaywarrior0
Copy link
Author

I did it basically like this

        public void boostSpeed()
        {
            Rigidbody rb = gameObject.GetComponent<Rigidbody>();
            rb.velocity = rb.transform.forward * (60 / 3.6f);
        }

And for the spawnpoints, i found a way to put them on Traffic System Gizmos, i took the code from TrafficSystemGizmos.cs and edited for my purpose.

using System;
using System.Linq;
using UnityEngine;

namespace TrafficSimulation
{
    public class SpawnCreator : MonoBehaviour
    {
        public GameObject myPrefab;
        public TrafficSystem script;

        void Start()
        {
            Spawnn(script);
        }
        public void Spawnn(TrafficSystem script)
        {

            foreach (Segment segment in script.segments)
            {
                GUIStyle style = new GUIStyle { normal = { textColor = new Color(1, 0, 0) }, fontSize = 15 };

                //Draw waypoint
                for (int j = 0; j < segment.waypoints.Count; j++)
                {
                    //Get current waypoint position
                    Vector3 p = segment.waypoints[j].GetVisualPos();


                    //Get next waypoint position
                    Vector3 pNext = Vector3.zero;

                    if (j < segment.waypoints.Count - 1 && segment.waypoints[j + 1] != null)
                    {
                        pNext = segment.waypoints[j + 1].GetVisualPos();
                    }

                    if (pNext != Vector3.zero)
                    {
                        if (segment == script.curSegment)
                        {
                            Gizmos.color = new Color(1f, .3f, .1f);
                        }
                        else
                        {
                            Gizmos.color = new Color(1f, 0f, 0f);
                        }


                        //Set arrow count based on arrowDrawType
                        int arrows = GetArrowCount(p, pNext, script);

                        //Draw arrows
                        for (int i = 1; i < arrows + 1; i++)
                        {
                            Vector3 point = Vector3.Lerp(p, pNext, (float)i / (arrows + 1));
                            GameObject abu = Instantiate(myPrefab, point, Quaternion.LookRotation(p - pNext));
                            abu.transform.rotation = abu.transform.rotation * Quaternion.Euler(0, 180, 0);
                        }
                    }
                }

            }
        }



        private int GetArrowCount(Vector3 pointA, Vector3 pointB, TrafficSystem script)
        {
            switch (script.arrowDrawType)
            {
                case ArrowDraw.FixedCount:
                    return script.arrowCount;
                case ArrowDraw.ByLength:
                    //Minimum of one arrow
                    return Mathf.Max(1, (int)(Vector3.Distance(pointA, pointB) / script.arrowDistance));
                case ArrowDraw.Off:
                    return 0;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
    }
}

But thanks anyway for the script

@highwaywarrior0
Copy link
Author

Now im working on enabling the spawnpoints only when player is close to them, and destroy traffic cars when they are far behind player.

@highwaywarrior0
Copy link
Author

I did everything i wanted. Now it never gets under 100 fps with roads full of traffic. Before all these optimizing stuff it were starting with ~40 fps then slowly decreasing untill like 10-15 fps

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants