Из-за скрита начинаются дикие лаги.

Раздел, посвящённый самому важному - скорости.

Из-за скрита начинаются дикие лаги.

Сообщение mrCraick 23 ноя 2016, 18:02

Скрытый текст:
Всем привет вообщем проблема такова, что во время игры после нескольких загрузок сцен(причем арн не прикрошался сцены из скриптов переключались), один скрипт начинает очень сильно загружать систему. Отклик возрастает до 500 - 12000 ms и играть становится не возможно. Почему так происходит я вообще не понимаю.
Ниже скрин, во время лагов. Причем они начинаются в самом начале, после загрузки сцены.
Изображение
Синтаксис:
Используется csharp
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(DriveForce))]
[ExecuteInEditMode]
[DisallowMultipleComponent]
[AddComponentMenu("RVP/C#/Drivetrain/Wheel", 1)]

//Class for the wheel
public class Wheel : MonoBehaviour
{
        [System.NonSerialized]
        public Transform tr;
        Rigidbody rb;
        [System.NonSerialized]
        public VehicleParent vp;
        [System.NonSerialized]
        public Suspension suspensionParent;
        [System.NonSerialized]
        public Transform rim;
        Transform tire;
        Vector3 localVel;

        [Tooltip("Generate a sphere collider to represent the wheel for side collisions")]
        public bool generateHardCollider = true;
        SphereCollider sphereCol;//Hard collider
        Transform sphereColTr;//Hard collider transform

        [Header("Rotation")]

        [Tooltip("Bias for feedback RPM lerp between target RPM and raw RPM")]
        [Range(0, 1)]
        public float feedbackRpmBias;

        [Tooltip("Curve for setting final RPM of wheel based on driving torque/brake force, x-axis = torque/brake force, y-axis = lerp between raw RPM and target RPM")]
        public AnimationCurve rpmBiasCurve = AnimationCurve.Linear(0, 0, 1, 1);

        [Tooltip("As the RPM of the wheel approaches this value, the RPM bias curve is interpolated with the default linear curve")]
        public float rpmBiasCurveLimit = Mathf.Infinity;

        [Range(0, 10)]
        public float axleFriction;

        [Header("Friction")]

    [Range(0, 1)]
    public float frictionSmoothness = 0.5f;
        public float forwardFriction = 1;
        public float sidewaysFriction = 1;
        public float forwardRimFriction = 0.5f;
        public float sidewaysRimFriction = 0.5f;
        public float forwardCurveStretch = 1;
        public float sidewaysCurveStretch = 1;
    Vector3 frictionForce = Vector3.zero;

    [Tooltip("X-axis = slip, y-axis = friction")]
        public AnimationCurve forwardFrictionCurve = AnimationCurve.Linear(0, 0, 1, 1);

        [Tooltip("X-axis = slip, y-axis = friction")]
        public AnimationCurve sidewaysFrictionCurve = AnimationCurve.Linear(0, 0, 1, 1);
        [System.NonSerialized]
        public float forwardSlip;
        [System.NonSerialized]
        public float sidewaysSlip;
        public enum SlipDependenceMode {dependent, forward, sideways, independent};
        public SlipDependenceMode slipDependence = SlipDependenceMode.sideways;
        [Range(0, 2)]
        public float forwardSlipDependence = 2;
        [Range(0, 2)]
        public float sidewaysSlipDependence = 2;

        [Tooltip("Adjusts how much friction the wheel has based on the normal of the ground surface. X-axis = normal dot product, y-axis = friction multiplier")]
        public AnimationCurve normalFrictionCurve = AnimationCurve.Linear(0, 1, 1, 1);

        [Header("Size")]

        public float tireRadius;
        public float rimRadius;
        public float tireWidth;
        public float rimWidth;

        [System.NonSerialized]
        public float setTireWidth;
        [System.NonSerialized]
        public float tireWidthPrev;
        [System.NonSerialized]
        public float setTireRadius;
        [System.NonSerialized]
        public float tireRadiusPrev;

        [System.NonSerialized]
        public float setRimWidth;
        [System.NonSerialized]
        public float rimWidthPrev;
        [System.NonSerialized]
        public float setRimRadius;
        [System.NonSerialized]
        public float rimRadiusPrev;

        [System.NonSerialized]
        public float actualRadius;

        [Header("Tire")]

        [Range(0, 1)]
        public float tirePressure = 1;
        [System.NonSerialized]
        public float setTirePressure;
        [System.NonSerialized]
        public float tirePressurePrev;
        float initialTirePressure;
        public bool popped;
        [System.NonSerialized]
        public bool setPopped;
        [System.NonSerialized]
        public bool poppedPrev;
        public bool canPop;

        [Tooltip("Requires deform shader")]
        public float deformAmount;
        Material rimMat;
        Material tireMat;
        float airLeakTime = -1;

        [Range(0, 1)]
        public float rimGlow;
        float glowAmount;
        Color glowColor;

        [System.NonSerialized]
        public bool updatedSize;
        [System.NonSerialized]
        public bool updatedPopped;

        float currentRPM;
        [System.NonSerialized]
        public DriveForce targetDrive;
        [System.NonSerialized]
        public float rawRPM;//RPM based purely on velocity
        [System.NonSerialized]
        public WheelContact contactPoint = new WheelContact();
        [System.NonSerialized]
        public bool getContact = true;//Should the wheel try to get contact info?
        [System.NonSerialized]
        public bool grounded;
        float airTime;
        [System.NonSerialized]
        public float travelDist;
        Vector3 upDir;//Up direction
        float circumference;

        [System.NonSerialized]
        public Vector3 contactVelocity;//Velocity of contact point
        float actualEbrake;
        float actualTargetRPM;
        float actualTorque;

        [System.NonSerialized]
        public Vector3 forceApplicationPoint;//Point at which friction forces are applied

        [Tooltip("Apply friction forces at ground point")]
        public bool applyForceAtGroundContact;

        [Header("Audio")]

        public AudioSource impactSnd;
        public AudioClip[] tireHitClips;
        public AudioClip rimHitClip;
        public AudioClip tireAirClip;
        public AudioClip tirePopClip;

        [Header("Damage")]

        public float detachForce = Mathf.Infinity;
        [System.NonSerialized]
        public float damage;
        public float mass = 0.05f;
        [System.NonSerialized]
        public bool canDetach;
        [System.NonSerialized]
        public bool connected = true;
       
        public Mesh tireMeshLoose;//Tire mesh for detached wheel collider
        public Mesh rimMeshLoose;//Rim mesh for detached wheel collider
        GameObject detachedWheel;
        GameObject detachedTire;
        MeshCollider detachedCol;
        Rigidbody detachedBody;
        MeshFilter detachFilter;
        MeshFilter detachTireFilter;
        public PhysicMaterial detachedTireMaterial;
        public PhysicMaterial detachedRimMaterial;

    void Start()
        {
                tr = transform;
                rb = &#40;Rigidbody&#41;F.GetTopmostParentComponent<Rigidbody>&#40;tr&#41;;
                vp = &#40;VehicleParent&#41;F.GetTopmostParentComponent<VehicleParent>&#40;tr&#41;;
                suspensionParent = tr.parent.GetComponent<Suspension>&#40;&#41;;
                travelDist = suspensionParent.targetCompression;
                canDetach = detachForce < Mathf.Infinity && Application.isPlaying;
                initialTirePressure = tirePressure;

                if &#40;tr.childCount > 0&#41;
                {
                        //Get rim
                        rim = tr.GetChild&#40;0&#41;;

                        //Set up rim glow material
                        if &#40;rimGlow > 0 && Application.isPlaying&#41;
                        {
                                rimMat = new Material&#40;rim.GetComponent<MeshRenderer>&#40;&#41;.sharedMaterial&#41;;
                                rimMat.EnableKeyword&#40;"_EMISSION"&#41;;
                                rim.GetComponent<MeshRenderer>&#40;&#41;.material = rimMat;
                        }

                        //Create detached wheel
                        if &#40;canDetach&#41;
                        {
                                detachedWheel = new GameObject&#40;vp.transform.name + "&#39;s Detached Wheel"&#41;;
                                detachedWheel.layer = LayerMask.NameToLayer&#40;"Detachable Part"&#41;;
                                detachFilter = detachedWheel.AddComponent<MeshFilter>&#40;&#41;;
                                detachFilter.sharedMesh = rim.GetComponent<MeshFilter>&#40;&#41;.sharedMesh;
                                MeshRenderer detachRend = detachedWheel.AddComponent<MeshRenderer>&#40;&#41;;
                                detachRend.sharedMaterial = rim.GetComponent<MeshRenderer>&#40;&#41;.sharedMaterial;
                                detachedCol = detachedWheel.AddComponent<MeshCollider>&#40;&#41;;
                                detachedCol.convex = true;
                                detachedBody = detachedWheel.AddComponent<Rigidbody>&#40;&#41;;
                                detachedBody.mass = mass;
                        }

                        //Get tire
                        if &#40;rim.childCount > 0&#41;
                        {
                                tire = rim.GetChild&#40;0&#41;;
                                if &#40;deformAmount > 0 && Application.isPlaying&#41;
                                {
                                        tireMat = new Material&#40;tire.GetComponent<MeshRenderer>&#40;&#41;.sharedMaterial&#41;;
                                        tire.GetComponent<MeshRenderer>&#40;&#41;.material = tireMat;
                                }

                                //Create detached tire
                                if &#40;canDetach&#41;
                                {
                                        detachedTire = new GameObject&#40;"Detached Tire"&#41;;
                                        detachedTire.transform.parent = detachedWheel.transform;
                                        detachedTire.transform.localPosition = Vector3.zero;
                                        detachedTire.transform.localRotation = Quaternion.identity;
                                        detachTireFilter = detachedTire.AddComponent<MeshFilter>&#40;&#41;;
                                        detachTireFilter.sharedMesh = tire.GetComponent<MeshFilter>&#40;&#41;.sharedMesh;
                                        MeshRenderer detachTireRend = detachedTire.AddComponent<MeshRenderer>&#40;&#41;;
                                        detachTireRend.sharedMaterial = tireMat ? tireMat : tire.GetComponent<MeshRenderer>&#40;&#41;.sharedMaterial;
                                }
                        }

                        if &#40;Application.isPlaying&#41;
                        {
                                //Generate hard collider
                                if &#40;generateHardCollider&#41;
                                {
                                        GameObject sphereColNew = new GameObject&#40;"Rim Collider"&#41;;
                                        sphereColNew.layer = GlobalControl.ignoreWheelCastLayer;
                                        sphereColTr = sphereColNew.transform;
                                        sphereCol = sphereColNew.AddComponent<SphereCollider>&#40;&#41;;
                                        sphereColTr.parent = tr;
                                        sphereColTr.localPosition = Vector3.zero;
                                        sphereColTr.localRotation = Quaternion.identity;
                                        sphereCol.radius = Mathf.Min&#40;rimWidth * 0.5f, rimRadius * 0.5f&#41;;
                                        sphereCol.material = GlobalControl.frictionlessMatStatic;
                                }

                                if &#40;canDetach&#41;
                                {
                                        detachedWheel.SetActive&#40;false&#41;;
                                }
                        }
                }

                targetDrive = GetComponent<DriveForce>&#40;&#41;;
                currentRPM = 0;
        }

        void FixedUpdate&#40;&#41;
        {
                upDir = tr.up;
                actualRadius = popped ? rimRadius : Mathf.Lerp&#40;rimRadius, tireRadius, tirePressure&#41;;
                circumference = Mathf.PI * actualRadius * 2;
                localVel = rb.GetPointVelocity&#40;forceApplicationPoint&#41;;

                //Get proper inputs
                actualEbrake = suspensionParent.ebrakeEnabled ? suspensionParent.ebrakeForce : 0;
                actualTargetRPM = targetDrive.rpm * &#40;suspensionParent.driveInverted ? -1 : 1&#41;;
                actualTorque = suspensionParent.driveEnabled ? Mathf.Lerp&#40;targetDrive.torque, Mathf.Abs&#40;vp.accelInput&#41;, vp.burnout&#41; : 0;

                if &#40;getContact&#41;
                {
                        GetWheelContact&#40;&#41;;
                }
                else if &#40;grounded&#41;
                {
                        contactPoint.point += localVel * Time.fixedDeltaTime;
                }

                airTime = grounded ? 0 : airTime + Time.fixedDeltaTime;
                forceApplicationPoint = applyForceAtGroundContact ? contactPoint.point : tr.position;

                if &#40;connected&#41;
                {
                        GetRawRPM&#40;&#41;;
                        ApplyDrive&#40;&#41;;
                }
                else
                {
                        rawRPM = 0;
                        currentRPM = 0;
            targetDrive.feedbackRPM = 0;
        }

                //Get travel distance
                travelDist = suspensionParent.compression < travelDist || grounded ? suspensionParent.compression : Mathf.Lerp&#40;travelDist, suspensionParent.compression, suspensionParent.extendSpeed * Time.fixedDeltaTime&#41;;

                PositionWheel&#40;&#41;;

                if &#40;connected&#41;
                {
                        //Update hard collider size upon changed radius or width
                        if &#40;generateHardCollider&#41;
                        {
                                setRimWidth = rimWidth;
                                setRimRadius = rimRadius;
                                setTireWidth = tireWidth;
                                setTireRadius = tireRadius;
                                setTirePressure = tirePressure;

                                if &#40;rimWidthPrev != setRimWidth || rimRadiusPrev != setRimRadius&#41;
                                {
                                        sphereCol.radius = Mathf.Min&#40;rimWidth * 0.5f, rimRadius * 0.5f&#41;;
                                        updatedSize = true;
                                }
                                else if &#40;tireWidthPrev != setTireWidth || tireRadiusPrev != setTireRadius || tirePressurePrev != setTirePressure&#41;
                                {
                                        updatedSize = true;
                                }
                                else
                                {
                                        updatedSize = false;
                                }

                                rimWidthPrev = setRimWidth;
                                rimRadiusPrev = setRimRadius;
                                tireWidthPrev = setTireWidth;
                                tireRadiusPrev = setTireRadius;
                                tirePressurePrev = setTirePressure;
                        }

                        GetSlip&#40;&#41;;
                        ApplyFriction&#40;&#41;;

                        //Burnout spinning
                        if &#40;vp.burnout > 0 && targetDrive.rpm != 0 && actualEbrake * vp.ebrakeInput == 0 && connected && grounded&#41;
                        {
                                rb.AddForceAtPosition&#40;suspensionParent.forwardDir * -suspensionParent.flippedSideFactor * &#40;vp.steerInput * vp.burnoutSpin * currentRPM * Mathf.Min&#40;0.1f, targetDrive.torque&#41; * 0.001f&#41; * vp.burnout * &#40;popped ? 0.5f : 1&#41; * contactPoint.surfaceFriction, suspensionParent.tr.position, ForceMode.Acceleration&#41;;
                        }

                        //Popping logic
                        setPopped = popped;

                        if &#40;poppedPrev != setPopped&#41;
                        {
                                if &#40;tire&#41;
                                {
                                        tire.gameObject.SetActive&#40;!popped&#41;;
                                }
                               
                                updatedPopped = true;
                        }
                        else
                        {
                                updatedPopped = false;
                        }

                        poppedPrev = setPopped;

                        //Air leak logic
                        if &#40;airLeakTime >= 0&#41;
                        {
                                tirePressure = Mathf.Clamp01&#40;tirePressure - Time.fixedDeltaTime * 0.5f&#41;;

                                if &#40;grounded&#41;
                                {
                                        airLeakTime += Mathf.Max&#40;Mathf.Abs&#40;currentRPM&#41; * 0.001f, localVel.magnitude * 0.1f&#41; * Time.timeScale * TimeMaster.inverseFixedTimeFactor;

                                        if &#40;airLeakTime > 1000  && tirePressure == 0&#41;
                                        {
                                                popped = true;
                                                airLeakTime = -1;

                                                if &#40;impactSnd && tirePopClip&#41;
                                                {
                                                        impactSnd.PlayOneShot&#40;tirePopClip&#41;;
                                                        impactSnd.pitch = 1;
                                                }
                                        }
                                }
                        }
                }
        }
       
        void Update&#40;&#41;
        {
                RotateWheel&#40;&#41;;

                if &#40;!Application.isPlaying&#41;
                {
                        PositionWheel&#40;&#41;;
                }
                else
                {
                        if &#40;deformAmount > 0 && tireMat && connected&#41;
                        {
                                if &#40;tireMat.HasProperty&#40;"_DeformNormal"&#41;&#41;
                                {
                                        //Deform tire &#40;requires deform shader&#41;
                                        Vector3 deformNormal = grounded ? contactPoint.normal * Mathf.Max&#40;-suspensionParent.penetration * &#40;1 - suspensionParent.compression&#41; * 10, 1 - tirePressure&#41; * deformAmount : Vector3.zero;
                                        tireMat.SetVector&#40;"_DeformNormal", new Vector4&#40;deformNormal.x, deformNormal.y, deformNormal.z, 0&#41;&#41;;
                                }
                        }

                        if &#40;rimMat&#41;
                        {
                                if &#40;rimMat.HasProperty&#40;"_EmissionColor"&#41;&#41;
                                {
                                        //Make the rim glow
                                        float targetGlow = connected && GroundSurfaceMaster.surfaceTypesStatic[contactPoint.surfaceType].leaveSparks ? Mathf.Abs&#40;F.MaxAbs&#40;forwardSlip, sidewaysSlip&#41;&#41; : 0;
                                        glowAmount = popped ? Mathf.Lerp&#40;glowAmount, targetGlow, &#40;targetGlow > glowAmount ? 2 : 0.2f&#41; * Time.deltaTime&#41; : 0;
                                        glowColor = new Color&#40;glowAmount, glowAmount * 0.5f, 0&#41;;
                                        rimMat.SetColor&#40;"_EmissionColor", popped ? Color.Lerp&#40;Color.black, glowColor, glowAmount * rimGlow&#41; : Color.black&#41;;
                                }
                        }
                }
        }
       
        void GetWheelContact&#40;&#41;
        {
        float castDist = Mathf.Max&#40;suspensionParent.suspensionDistance * Mathf.Max&#40;0.001f, suspensionParent.targetCompression&#41; + actualRadius, 0.001f&#41;;
        RaycastHit[] wheelHits = Physics.RaycastAll&#40;suspensionParent.maxCompressPoint, suspensionParent.springDirection, castDist, GlobalControl.wheelCastMaskStatic&#41;;
        RaycastHit hit;
                int hitIndex = 0;
                bool validHit = false;
                float hitDist = Mathf.Infinity;

                if &#40;connected&#41;
                {
                        //Loop through raycast hits to find closest one
                        for &#40;int i = 0; i < wheelHits.Length; i++&#41;
                        {
                                if &#40;!wheelHits[i].transform.IsChildOf&#40;vp.tr&#41; && wheelHits[i].distance < hitDist&#41;
                                {
                                        hitIndex = i;
                                        hitDist = wheelHits[i].distance;
                                        validHit = true;
                                }
                        }
                }
                else
                {
                        validHit = false;
                }

                //Set contact point variables
                if &#40;validHit&#41;
                {
                        hit = wheelHits[hitIndex];

                        if &#40;!grounded && impactSnd && &#40;&#40;tireHitClips.Length > 0 && !popped&#41; || &#40;rimHitClip && popped&#41;&#41;&#41;
                        {
                                impactSnd.PlayOneShot&#40;popped ? rimHitClip : tireHitClips[Mathf.RoundToInt&#40;Random.Range&#40;0, tireHitClips.Length - 1&#41;&#41;], Mathf.Clamp01&#40;airTime * airTime&#41;&#41;;
                                impactSnd.pitch = Mathf.Clamp&#40;airTime * 0.2f + 0.8f, 0.8f, 1&#41;;
                        }

                        grounded = true;
                        contactPoint.distance = hit.distance - actualRadius;
                        contactPoint.point = hit.point + localVel * Time.fixedDeltaTime;
                        contactPoint.grounded = true;
                        contactPoint.normal = hit.normal;
                        contactPoint.relativeVelocity = tr.InverseTransformDirection&#40;localVel&#41;;
                        contactPoint.col = hit.collider;

                        if &#40;hit.collider.attachedRigidbody&#41;
                        {
                                contactVelocity = hit.collider.attachedRigidbody.GetPointVelocity&#40;contactPoint.point&#41;;
                                contactPoint.relativeVelocity -= tr.InverseTransformDirection&#40;contactVelocity&#41;;
                        }
                        else
                        {
                                contactVelocity = Vector3.zero;
                        }

                        GroundSurfaceInstance curSurface = hit.collider.GetComponent<GroundSurfaceInstance>&#40;&#41;;
                        TerrainSurface curTerrain = hit.collider.GetComponent<TerrainSurface>&#40;&#41;;

                        if &#40;curSurface&#41;
                        {
                                contactPoint.surfaceFriction = curSurface.friction;
                                contactPoint.surfaceType = curSurface.surfaceType;
                        }
                        else if &#40;curTerrain&#41;
                        {
                                contactPoint.surfaceType = curTerrain.GetDominantSurfaceTypeAtPoint&#40;contactPoint.point&#41;;
                                contactPoint.surfaceFriction = curTerrain.GetFriction&#40;contactPoint.surfaceType&#41;;
                        }
                        else
                        {
                                contactPoint.surfaceFriction = hit.collider.material.dynamicFriction * 2;
                                contactPoint.surfaceType = 0;
                        }

                        if &#40;contactPoint.col.CompareTag&#40;"Pop Tire"&#41; && canPop && airLeakTime == -1 && !popped&#41;
                        {
                                Deflate&#40;&#41;;
                        }
                }
                else
                {
                        grounded = false;
                        contactPoint.distance = suspensionParent.suspensionDistance;
                        contactPoint.point = Vector3.zero;
                        contactPoint.grounded = false;
                        contactPoint.normal = upDir;
                        contactPoint.relativeVelocity = Vector3.zero;
                        contactPoint.col = null;
                        contactVelocity = Vector3.zero;
                        contactPoint.surfaceFriction = 0;
                        contactPoint.surfaceType = 0;
                }
        }
       
        void GetRawRPM&#40;&#41;
        {
                if &#40;grounded&#41;
                {
                        rawRPM = &#40;contactPoint.relativeVelocity.x / circumference&#41; * &#40;Mathf.PI * 100&#41; * -suspensionParent.flippedSideFactor;
                }
                else
                {
                        rawRPM = Mathf.Lerp&#40;rawRPM, actualTargetRPM, &#40;actualTorque + suspensionParent.brakeForce * vp.brakeInput + actualEbrake * vp.ebrakeInput&#41; * Time.timeScale&#41;;
                }
        }
       
        void GetSlip&#40;&#41;
        {
                if &#40;grounded&#41;
                {
                        sidewaysSlip = &#40;contactPoint.relativeVelocity.z * 0.1f&#41; / sidewaysCurveStretch;
                        forwardSlip = &#40;0.01f * &#40;rawRPM - currentRPM&#41;&#41; / forwardCurveStretch;
                }
                else
                {
                        sidewaysSlip = 0;
                        forwardSlip = 0;
                }
        }
       
        void ApplyFriction&#40;&#41;
        {
                if &#40;grounded&#41;
                {
                        float forwardSlipFactor = &#40;int&#41;slipDependence == 0 || &#40;int&#41;slipDependence == 1 ? forwardSlip - sidewaysSlip : forwardSlip;
                        float sidewaysSlipFactor = &#40;int&#41;slipDependence == 0 || &#40;int&#41;slipDependence == 2 ? sidewaysSlip - forwardSlip : sidewaysSlip;
                        float forwardSlipDependenceFactor = Mathf.Clamp01&#40;forwardSlipDependence - Mathf.Clamp01&#40;Mathf.Abs&#40;sidewaysSlip&#41;&#41;&#41;;
                        float sidewaysSlipDependenceFactor = Mathf.Clamp01&#40;sidewaysSlipDependence - Mathf.Clamp01&#40;Mathf.Abs&#40;forwardSlip&#41;&#41;&#41;;

                        frictionForce = Vector3.Lerp&#40;frictionForce,
                    tr.TransformDirection&#40;
                                            forwardFrictionCurve.Evaluate&#40;Mathf.Abs&#40;forwardSlipFactor&#41;&#41; * -System.Math.Sign&#40;forwardSlip&#41; * &#40;popped ? forwardRimFriction : forwardFriction&#41; * forwardSlipDependenceFactor * -suspensionParent.flippedSideFactor
                                            , 0
                                            , sidewaysFrictionCurve.Evaluate&#40;Mathf.Abs&#40;sidewaysSlipFactor&#41;&#41; * -System.Math.Sign&#40;sidewaysSlip&#41; * &#40;popped ? sidewaysRimFriction : sidewaysFriction&#41; * sidewaysSlipDependenceFactor * normalFrictionCurve.Evaluate&#40;Mathf.Clamp01&#40;Vector3.Dot&#40;contactPoint.normal, GlobalControl.worldUpDir&#41;&#41;&#41; * &#40;vp.burnout > 0 && Mathf.Abs&#40;targetDrive.rpm&#41; != 0 && actualEbrake * vp.ebrakeInput == 0 && grounded ? &#40;1 - vp.burnout&#41; * &#40;1 - Mathf.Abs&#40;vp.accelInput&#41;&#41; : 1&#41;&#41;
                                    * &#40;0.5f + &#40;1 - suspensionParent.compression&#41; * 0.5f * Mathf.Clamp01&#40;Mathf.Abs&#40;suspensionParent.tr.InverseTransformDirection&#40;localVel&#41;.z&#41; * 10&#41;&#41; * contactPoint.surfaceFriction
                , 1 - frictionSmoothness&#41;;

                        rb.AddForceAtPosition&#40;frictionForce, forceApplicationPoint, ForceMode.Acceleration&#41;;

                        //If resting on a rigidbody, apply opposing force to it
                        if &#40;contactPoint.col.attachedRigidbody&#41;
                        {
                                contactPoint.col.attachedRigidbody.AddForceAtPosition&#40;-frictionForce, contactPoint.point, ForceMode.Acceleration&#41;;
                        }
                }
        }
       
        void ApplyDrive&#40;&#41;
        {
                float brakeForce = 0;
                float brakeCheckValue = suspensionParent.skidSteerBrake ? vp.localAngularVel.y : vp.localVelocity.z;

                //Set brake force
                if &#40;vp.brakeIsReverse&#41;
                {
                        if &#40;brakeCheckValue > 0&#41;
                        {
                                brakeForce = suspensionParent.brakeForce * vp.brakeInput;
                        }
                        else if &#40;brakeCheckValue <= 0&#41;
                        {
                                brakeForce = suspensionParent.brakeForce * Mathf.Clamp01&#40;vp.accelInput&#41;;
                        }
                }
                else
                {
                        brakeForce = suspensionParent.brakeForce * vp.brakeInput;
                }
               
                brakeForce += axleFriction * 0.1f * &#40;Mathf.Approximately&#40;actualTorque, 0&#41; ? 1 : 0&#41;;

                if &#40;targetDrive.rpm != 0&#41;
                {
                        brakeForce *= &#40;1 - vp.burnout&#41;;
                }

                //Set final RPM
                if &#40;!suspensionParent.jammed && connected&#41;
                {
                        bool validTorque = &#40;!&#40;Mathf.Approximately&#40;actualTorque, 0&#41; && Mathf.Abs&#40;actualTargetRPM&#41; < 0.01f&#41; && !Mathf.Approximately&#40;actualTargetRPM, 0&#41;&#41; || brakeForce + actualEbrake * vp.ebrakeInput > 0;

                        currentRPM = Mathf.Lerp&#40;rawRPM,
                                Mathf.Lerp&#40;
                                Mathf.Lerp&#40;rawRPM, actualTargetRPM, validTorque ? EvaluateTorque&#40;actualTorque&#41; : actualTorque&#41;
                                , 0, Mathf.Max&#40;brakeForce, actualEbrake * vp.ebrakeInput&#41;&#41;
                        , validTorque ? EvaluateTorque&#40;actualTorque + brakeForce + actualEbrake * vp.ebrakeInput&#41; : actualTorque + brakeForce + actualEbrake * vp.ebrakeInput&#41;;

                        targetDrive.feedbackRPM = Mathf.Lerp&#40;currentRPM, rawRPM, feedbackRpmBias&#41;;
                }
                else
                {
                        currentRPM = 0;
            targetDrive.feedbackRPM = 0;
        }
        }

        //Extra method for evaluating torque to make the ApplyDrive method more readable
        float EvaluateTorque&#40;float t&#41;
        {
                float torque = Mathf.Lerp&#40;rpmBiasCurve.Evaluate&#40;t&#41;, t, rawRPM / &#40;rpmBiasCurveLimit * Mathf.Sign&#40;actualTargetRPM&#41;&#41;&#41;;
                return torque;
        }
       
        void PositionWheel&#40;&#41;
        {
                if &#40;suspensionParent&#41;
                {
                        rim.position = suspensionParent.maxCompressPoint + suspensionParent.springDirection * suspensionParent.suspensionDistance * &#40;Application.isPlaying ? travelDist : suspensionParent.targetCompression&#41; +
                                suspensionParent.upDir * Mathf.Pow&#40;Mathf.Max&#40;Mathf.Abs&#40;Mathf.Sin&#40;suspensionParent.sideAngle * Mathf.Deg2Rad&#41;&#41;, Mathf.Abs&#40;Mathf.Sin&#40;suspensionParent.casterAngle * Mathf.Deg2Rad&#41;&#41;&#41;, 2&#41; * actualRadius +
                                suspensionParent.pivotOffset * suspensionParent.tr.TransformDirection&#40;Mathf.Sin&#40;tr.localEulerAngles.y * Mathf.Deg2Rad&#41;, 0, Mathf.Cos&#40;tr.localEulerAngles.y * Mathf.Deg2Rad&#41;&#41;
                                - suspensionParent.pivotOffset * &#40;Application.isPlaying ? suspensionParent.forwardDir : suspensionParent.tr.forward&#41;;
                }

                if &#40;Application.isPlaying && generateHardCollider && connected&#41;
                {
                        //sphereColTr.position = rim.position;
                }
        }

        void RotateWheel&#40;&#41;
        {
                if &#40;tr && suspensionParent&#41;
                {
                        float ackermannVal = Mathf.Sign&#40;suspensionParent.steerAngle&#41; == suspensionParent.flippedSideFactor ? 1 + suspensionParent.ackermannFactor : 1 - suspensionParent.ackermannFactor;
                        tr.localEulerAngles = new Vector3&#40;suspensionParent.camberAngle + suspensionParent.casterAngle * suspensionParent.steerAngle * suspensionParent.flippedSideFactor, -suspensionParent.toeAngle * suspensionParent.flippedSideFactor + suspensionParent.steerDegrees * ackermannVal, 0&#41;;
                }

                if &#40;Application.isPlaying&#41;
                {
                        rim.Rotate&#40;Vector3.forward, currentRPM * suspensionParent.flippedSideFactor * Time.deltaTime&#41;;

                        if &#40;damage > 0&#41;
                        {
                                rim.localEulerAngles = new Vector3&#40;Mathf.Sin&#40;-rim.localEulerAngles.z * Mathf.Deg2Rad&#41; * Mathf.Clamp&#40;damage, 0, 10&#41;, Mathf.Cos&#40;-rim.localEulerAngles.z * Mathf.Deg2Rad&#41; * Mathf.Clamp&#40;damage, 0, 10&#41;, rim.localEulerAngles.z&#41;;
                        }
                        else if &#40;rim.localEulerAngles.x != 0 || rim.localEulerAngles.y != 0&#41;
                        {
                                rim.localEulerAngles = new Vector3&#40;0, 0, rim.localEulerAngles.z&#41;;
                        }
                }
        }

        public void Deflate&#40;&#41;
        {
                airLeakTime = 0;
               
                if &#40;impactSnd && tireAirClip&#41;
                {
                        impactSnd.PlayOneShot&#40;tireAirClip&#41;;
                        impactSnd.pitch = 1;
                }
        }

        public void FixTire&#40;&#41;
        {
                popped = false;
                tirePressure = initialTirePressure;
                airLeakTime = -1;
        }

        public void Detach&#40;&#41;
        {
                if &#40;connected && canDetach&#41;
                {
                        connected = false;
                        detachedWheel.SetActive&#40;true&#41;;
                        detachedWheel.transform.position = rim.position;
                        detachedWheel.transform.rotation = rim.rotation;
                        detachedCol.sharedMaterial = popped ? detachedRimMaterial : detachedTireMaterial;

                        if &#40;tire&#41;
                        {
                                detachedTire.SetActive&#40;!popped&#41;;
                                detachedCol.sharedMesh = airLeakTime >= 0 || popped ? &#40;rimMeshLoose ? rimMeshLoose : detachFilter.sharedMesh&#41; : &#40;tireMeshLoose ? tireMeshLoose : detachTireFilter.sharedMesh&#41;;
                        }
                        else
                        {
                                detachedCol.sharedMesh = rimMeshLoose ? rimMeshLoose : detachFilter.sharedMesh;
                        }
                       
                        rb.mass -= mass;
                        detachedBody.velocity = rb.GetPointVelocity&#40;rim.position&#41;;
                        detachedBody.angularVelocity = rb.angularVelocity;

                        rim.gameObject.SetActive&#40;false&#41;;

                        if &#40;sphereColTr&#41;
                        {
                                sphereColTr.gameObject.SetActive&#40;false&#41;;
                        }
                }
        }

        //Automatically sets wheel dimensions based on rim/tire meshes
        public void GetWheelDimensions&#40;float radiusMargin, float widthMargin&#41;
        {
                Mesh rimMesh = null;
                Mesh tireMesh = null;
                Mesh checker;
                Transform scaler = transform;

                if &#40;transform.childCount > 0&#41;
                {
                        if &#40;transform.GetChild&#40;0&#41;.GetComponent<MeshFilter>&#40;&#41;&#41;
                        {
                                rimMesh = transform.GetChild&#40;0&#41;.GetComponent<MeshFilter>&#40;&#41;.sharedMesh;
                                scaler = transform.GetChild&#40;0&#41;;
                        }

                        if &#40;transform.GetChild&#40;0&#41;.childCount > 0&#41;
                        {
                                if &#40;transform.GetChild&#40;0&#41;.GetChild&#40;0&#41;.GetComponent<MeshFilter>&#40;&#41;&#41;
                                {
                                        tireMesh = transform.GetChild&#40;0&#41;.GetChild&#40;0&#41;.GetComponent<MeshFilter>&#40;&#41;.sharedMesh;
                                }
                        }

                        checker = tireMesh ? tireMesh : rimMesh;

                        if &#40;checker&#41;
                        {
                                float maxWidth = 0;
                                float maxRadius = 0;

                                foreach &#40;Vector3 curVert in checker.vertices&#41;
                                {
                                        if &#40;new Vector2&#40;curVert.x * scaler.localScale.x, curVert.y * scaler.localScale.y&#41;.magnitude > maxRadius&#41;
                                        {
                                                maxRadius = new Vector2&#40;curVert.x * scaler.localScale.x, curVert.y * scaler.localScale.y&#41;.magnitude;
                                        }

                                        if &#40;Mathf.Abs&#40;curVert.z * scaler.localScale.z&#41; > maxWidth&#41;
                                        {
                                                maxWidth = Mathf.Abs&#40;curVert.z * scaler.localScale.z&#41;;
                                        }
                                }

                                tireRadius = maxRadius + radiusMargin;
                                tireWidth = maxWidth + widthMargin;

                                if &#40;tireMesh && rimMesh&#41;
                                {
                                        maxWidth = 0;
                                        maxRadius = 0;

                                        foreach &#40;Vector3 curVert in rimMesh.vertices&#41;
                                        {
                                                if &#40;new Vector2&#40;curVert.x * scaler.localScale.x, curVert.y * scaler.localScale.y&#41;.magnitude > maxRadius&#41;
                                                {
                                                        maxRadius = new Vector2&#40;curVert.x * scaler.localScale.x, curVert.y * scaler.localScale.y&#41;.magnitude;
                                                }
                                               
                                                if &#40;Mathf.Abs&#40;curVert.z * scaler.localScale.z&#41; > maxWidth&#41;
                                                {
                                                        maxWidth = Mathf.Abs&#40;curVert.z * scaler.localScale.z&#41;;
                                                }
                                        }

                                        rimRadius = maxRadius + radiusMargin;
                                        rimWidth = maxWidth + widthMargin;
                                }
                                else
                                {
                                        rimRadius = maxRadius * 0.5f + radiusMargin;
                                        rimWidth = maxWidth * 0.5f + widthMargin;
                                }
                        }
                        else
                        {
                                Debug.LogError&#40;"No rim or tire meshes found for getting wheel dimensions.", this&#41;;
                        }
                }
        }

        public void Reattach&#40;&#41;
        {
                if &#40;!connected&#41;
                {
                        connected = true;
                        detachedWheel.SetActive&#40;false&#41;;
                        rb.mass += mass;
                        rim.gameObject.SetActive&#40;true&#41;;

                        if &#40;sphereColTr&#41;
                        {
                                sphereColTr.gameObject.SetActive&#40;true&#41;;
                        }
                }
        }

        //visualize wheel
        void OnDrawGizmosSelected&#40;&#41;
        {
                tr = transform;

                if &#40;tr.childCount > 0&#41;
                {
                        rim = tr.GetChild&#40;0&#41;;

                        if &#40;rim.childCount > 0&#41;
                        {
                                tire = rim.GetChild&#40;0&#41;;
                        }
                }

                float tireActualRadius = Mathf.Lerp&#40;rimRadius, tireRadius, tirePressure&#41;;

                if &#40;tirePressure < 1 && tirePressure > 0&#41;
                {
                        Gizmos.color = new Color&#40;1, 1, 0, popped ? 0.5f : 1&#41;;
                        GizmosExtra.DrawWireCylinder&#40;rim.position, rim.forward, tireActualRadius, tireWidth * 2&#41;;
                }

                Gizmos.color = Color.white;
                GizmosExtra.DrawWireCylinder&#40;rim.position, rim.forward, tireRadius, tireWidth * 2&#41;;

                Gizmos.color = tirePressure == 0 || popped ? Color.green : Color.cyan;
                GizmosExtra.DrawWireCylinder&#40;rim.position, rim.forward, rimRadius, rimWidth * 2&#41;;

                Gizmos.color = new Color&#40;1, 1, 1, tirePressure < 1 ? 0.5f : 1&#41;;
                GizmosExtra.DrawWireCylinder&#40;rim.position, rim.forward, tireRadius, tireWidth * 2&#41;;

                Gizmos.color = tirePressure == 0 || popped ? Color.green : Color.cyan;
                GizmosExtra.DrawWireCylinder&#40;rim.position, rim.forward, rimRadius, rimWidth * 2&#41;;
        }

        //Destroy detached wheel
        void OnDestroy&#40;&#41;
        {
                if &#40;Application.isPlaying&#41;
                {
                        if &#40;detachedWheel&#41;
                        {
                                Destroy&#40;detachedWheel&#41;;
                        }
                }
        }
}


//Contact point class
public class WheelContact
{
        public bool grounded;//Is the contact point grounded?
        public Collider col;//The collider of the contact point
        public Vector3 point;//The position of the contact point
        public Vector3 normal;//The normal of the contact point
        public Vector3 relativeVelocity;//Relative velocity between the wheel and the contact point object
        public float distance;//Distance from the suspension to the contact point minus the wheel radius
        public float surfaceFriction;//Friction of the contact surface
        public int surfaceType;//The surface type identified by the surface types array of GroundSurfaceMaster
}


Сразу скажу скрипт не мой, скрипт из ассета Randomation Vehicle Physics 2.0.
На мой вопрос они не отвечаю, вот решил у вас узнать, в чем омжет быть трабол.


Прощу топик удалить проблема была в том, что кто-то поставил FixedTime = 0.01.
mrCraick
UNец
 
Сообщения: 3
Зарегистрирован: 14 окт 2016, 21:55

Вернуться в Оптимизация

Кто сейчас на конференции

Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 2