1

У нас возникла небольшая проблема с Floating Origin и Edy's Vehicle Physics. Дело в том, что когда срабатывает Floating, физика Edy сильно «психует» Машину подкидывает, либо начинает крутить. Я нашла на форуме возможное решение, Код:

var v = rb.velocity;
var av = rb.angularVelocity;
rb.Sleep();
go.SetActive(false);
     
go.transform.position += offset;
     
go.SetActive(true);
rb.velocity = v;
rb.angularVelocity = av;

Но в силу того что я не сильна в программировании, то не понимаю как и куда применить кусочек кода. Я пыталась реализовать данный фрагмент кода в самом скрипте Floating Origin, но ничего не поменялось. Мои попытки решения: (только не ругайте сильно, я мало что знаю в программировании)

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using VehiclePhysics;
using EdyCommonTools;
using System.ComponentModel;
using UnityEngine.Serialization;

namespace VehiclePhysics
{
    [RequireComponent(typeof(Camera))]
    [AddComponentMenu("Vehicle Physics/Vehicle Controller", -21)]

    public class FloatingOrigin : MonoBehaviour
    {
        public float threshold = 100.0f;
        public float physicsThreshold = 1000.0f; // Set to zero to disable
        private RigidBody rb;
        private GameObject go;
        

        void Awake()
        {
            var v = rb.velocity;
            var av = rb.angularVelocity;
            rb.Sleep();
            go.SetActive(false);

            go.transform.position += Offset;

            go.SetActive(true);
            rb.velocity = v;
            rb.angularVelocity = av;
        }


#if OLD_PHYSICS
    public float defaultSleepVelocity = 0.14f;
    public float defaultAngularVelocity = 0.14f;
#else
        public float defaultSleepThreshold = 0.14f;
#endif

        ParticleSystem.Particle[] parts = null;
        private UnityEngine.Object[] objects;
        private Vector3 Offset;

        void LateUpdate()
        {
            Vector3 cameraPosition = gameObject.transform.position;
            cameraPosition.y = 0f;
            if (cameraPosition.magnitude > threshold)
            {
                for (int z = 0; z < SceneManager.sceneCount; z++)
                {
                    foreach (GameObject g in SceneManager.GetSceneAt(z).GetRootGameObjects())
                    {
                        g.transform.position -= cameraPosition;
                    }
                }

                //Object[] objects = FindObjectsOfType(typeof(Transform));
                //foreach (Object o in objects)
                //{
                //    Transform t = (Transform)o;
                //    if (t.parent == null)
                //    {
                //        t.position -= cameraPosition;
                //    }
                //}

#if SUPPORT_OLD_PARTICLE_SYSTEM
            // move active particles from old Unity particle system that are active in world space
            objects = FindObjectsOfType(typeof(ParticleEmitter));
            foreach (Object o in objects)
            {
                ParticleEmitter pe = (ParticleEmitter)o;
 
                // if the particle is not in world space, the logic above should have moved them already
        if (!pe.useWorldSpace)
            continue;
 
                Particle[] emitterParticles = pe.particles;
                for(int i = 0; i < emitterParticles.Length; ++i)
                {
                    emitterParticles[i].position -= cameraPosition;
                }
                pe.particles = emitterParticles;
            }
#endif

                // new particles... very similar to old version above
                objects = FindObjectsOfType(typeof(ParticleSystem));
                foreach (UnityEngine.Object o in objects)
                {
                    ParticleSystem sys = (ParticleSystem)o;

                    if (sys.simulationSpace != ParticleSystemSimulationSpace.World)
                        continue;

                    int particlesNeeded = sys.maxParticles;

                    if (particlesNeeded <= 0)
                        continue;

                    bool wasPaused = sys.isPaused;
                    bool wasPlaying = sys.isPlaying;

                    if (!wasPaused)
                        sys.Pause();

                    // ensure a sufficiently large array in which to store the particles
                    if (parts == null || parts.Length < particlesNeeded)
                    {
                        parts = new ParticleSystem.Particle[particlesNeeded];
                    }

                    // now get the particles
                    int num = sys.GetParticles(parts);

                    for (int i = 0; i < num; i++)
                    {
                        parts[i].position -= cameraPosition;
                    }

                    sys.SetParticles(parts, num);

                    if (wasPlaying)
                        sys.Play();
                }

                if (physicsThreshold > 0f)
                {
                    float physicsThreshold2 = physicsThreshold * physicsThreshold; // simplify check on threshold
                    objects = FindObjectsOfType(typeof(Rigidbody));
                    foreach (UnityEngine.Object o in objects)
                    {
                        Rigidbody r = (Rigidbody)o;
                        if (r.gameObject.transform.position.sqrMagnitude > physicsThreshold2)
                        {
#if OLD_PHYSICS
                        r.sleepAngularVelocity = float.MaxValue;
                        r.sleepVelocity = float.MaxValue;
#else
                            r.sleepThreshold = float.MaxValue;
#endif
                        }
                        else
                        {
#if OLD_PHYSICS
                        r.sleepAngularVelocity = defaultSleepVelocity;
                        r.sleepVelocity = defaultAngularVelocity;
#else
                            r.sleepThreshold = defaultSleepThreshold;
#endif
                        }
                    }
                }
            }
        }
    }
}

Может, кто наставит меня на путь истинный, подскажет, как и куда вставить данный фрагмент кода. Для полной картины записала видео "психов" физики Edy со скриптом FloatingOrigin https://vk.com/videos603696121?z=video603696121_456239020%2Fpl_603696121_-2

0

1 ответ 1

0

Если по простому то поменять название метода Awake на FixedUpdate

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using VehiclePhysics;
using EdyCommonTools;
using System.ComponentModel;
using UnityEngine.Serialization;

namespace VehiclePhysics
{
    [RequireComponent(typeof(Camera))]
    [AddComponentMenu("Vehicle Physics/Vehicle Controller", -21)]

    public class FloatingOrigin : MonoBehaviour
    {
        public float threshold = 100.0f;
        public float physicsThreshold = 1000.0f; // Set to zero to disable
        private RigidBody rb;
        private GameObject go;
        

        void FixedUpdate()
        {
            var v = rb.velocity;
            var av = rb.angularVelocity;
            rb.Sleep();
            go.SetActive(false);

            go.transform.position += Offset;

            go.SetActive(true);
            rb.velocity = v;
            rb.angularVelocity = av;
        }


#if OLD_PHYSICS
    public float defaultSleepVelocity = 0.14f;
    public float defaultAngularVelocity = 0.14f;
#else
        public float defaultSleepThreshold = 0.14f;
#endif

        ParticleSystem.Particle[] parts = null;
        private UnityEngine.Object[] objects;
        private Vector3 Offset;

        void LateUpdate()
        {
            Vector3 cameraPosition = gameObject.transform.position;
            cameraPosition.y = 0f;
            if (cameraPosition.magnitude > threshold)
            {
                for (int z = 0; z < SceneManager.sceneCount; z++)
                {
                    foreach (GameObject g in SceneManager.GetSceneAt(z).GetRootGameObjects())
                    {
                        g.transform.position -= cameraPosition;
                    }
                }

                //Object[] objects = FindObjectsOfType(typeof(Transform));
                //foreach (Object o in objects)
                //{
                //    Transform t = (Transform)o;
                //    if (t.parent == null)
                //    {
                //        t.position -= cameraPosition;
                //    }
                //}

#if SUPPORT_OLD_PARTICLE_SYSTEM
            // move active particles from old Unity particle system that are active in world space
            objects = FindObjectsOfType(typeof(ParticleEmitter));
            foreach (Object o in objects)
            {
                ParticleEmitter pe = (ParticleEmitter)o;
 
                // if the particle is not in world space, the logic above should have moved them already
        if (!pe.useWorldSpace)
            continue;
 
                Particle[] emitterParticles = pe.particles;
                for(int i = 0; i < emitterParticles.Length; ++i)
                {
                    emitterParticles[i].position -= cameraPosition;
                }
                pe.particles = emitterParticles;
            }
#endif

                // new particles... very similar to old version above
                objects = FindObjectsOfType(typeof(ParticleSystem));
                foreach (UnityEngine.Object o in objects)
                {
                    ParticleSystem sys = (ParticleSystem)o;

                    if (sys.simulationSpace != ParticleSystemSimulationSpace.World)
                        continue;

                    int particlesNeeded = sys.maxParticles;

                    if (particlesNeeded <= 0)
                        continue;

                    bool wasPaused = sys.isPaused;
                    bool wasPlaying = sys.isPlaying;

                    if (!wasPaused)
                        sys.Pause();

                    // ensure a sufficiently large array in which to store the particles
                    if (parts == null || parts.Length < particlesNeeded)
                    {
                        parts = new ParticleSystem.Particle[particlesNeeded];
                    }

                    // now get the particles
                    int num = sys.GetParticles(parts);

                    for (int i = 0; i < num; i++)
                    {
                        parts[i].position -= cameraPosition;
                    }

                    sys.SetParticles(parts, num);

                    if (wasPlaying)
                        sys.Play();
                }

                if (physicsThreshold > 0f)
                {
                    float physicsThreshold2 = physicsThreshold * physicsThreshold; // simplify check on threshold
                    objects = FindObjectsOfType(typeof(Rigidbody));
                    foreach (UnityEngine.Object o in objects)
                    {
                        Rigidbody r = (Rigidbody)o;
                        if (r.gameObject.transform.position.sqrMagnitude > physicsThreshold2)
                        {
#if OLD_PHYSICS
                        r.sleepAngularVelocity = float.MaxValue;
                        r.sleepVelocity = float.MaxValue;
#else
                            r.sleepThreshold = float.MaxValue;
#endif
                        }
                        else
                        {
#if OLD_PHYSICS
                        r.sleepAngularVelocity = defaultSleepVelocity;
                        r.sleepVelocity = defaultAngularVelocity;
#else
                            r.sleepThreshold = defaultSleepThreshold;
#endif
                        }
                    }
                }
            }
        }
    }
}
1
  • К сожалению, все так же продолжает "психовать" Физика Edy c FloatingOrigin. Записала видео этих самых "психов" vk.com/…
    – Niha Niha
    26 ноя 2020 в 21:16

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.