Как добиться кватернионного вращения с несколькими искусственными гравитационными телами (2D) - PullRequest
0 голосов
/ 11 апреля 2020

У меня есть скрипт (показанный ниже) для всех соответствующих тел, и я использую четверть, чтобы попытаться повернуть ноги спрайтов к земле ближайшего тела, но на самом деле происходит то, что независимо от того, к какому телу спрайт ближе всего , их ноги всегда направлены к одному и тому же телу, гравитационное моделирование отлично работает с несколькими телами, но не вращением, которое работает только так, как будто есть одно тело и игрок

ПРИМЕЧАНИЕ: этот скрипт выполняется в движке единства.

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

public class Attractor : MonoBehaviour
{
    const float G = 6.674f;//gravitational constant
    public Rigidbody2D rb;
    public static List<Attractor> attractorList;
    //public float closestAttractorDistance;
    public float distance;
    public Vector2 direction;
    public int RotationStrength = 10;

    private void Awake()
    {
        //closestAttractorDistance = 100000f;
    }

    private void OnEnable()//run on object enable
    {

        if (attractorList == null)//create list if it doesnt already exist
        {
            attractorList = new List<Attractor>();
        }
        attractorList.Add(this);

    }

    private void OnDisable()//pull from the list of the object leaving
    {
        attractorList.Remove(this);
    }

    private void FixedUpdate()
    {
        int i = 0;
        foreach (Attractor attractorObj in attractorList)
        {
            i++;
            if (attractorObj != this)//no need to give forces to planets as the are static atm
            {
                Debug.Log("Index: " + i + " Time: " + Time.realtimeSinceStartup.ToString());
                Attract(attractorObj);//attract the object its currently looking at
                //Debug.Log("Distance: " + closestAttractorDistance);         
            }
        }
    }

    void Attract(Attractor objToAttract)
    {        
        Rigidbody2D rbToAttract = objToAttract.rb;

        direction = rb.position - rbToAttract.position;
        Debug.Log("X: " + direction.x + " Y: " + direction.y);
        distance = direction.sqrMagnitude;//.Sqrmagnitude is the length of our direction vector


        if (distance == 0f)//prevent weird issues with own attractor
        {
            return;
        }   

        float forceMagnitude = G * (rb.mass * rbToAttract.mass) / distance;//using neutons mass of the two objects mlutiplied together and then divided by the distance sqaured with sqrMagnitude
        Vector2 force = direction.normalized * forceMagnitude;// apply a force in the direction of our object with a strength defined by neutons equation
        if (this.tag == "Planets")
        {
            Debug.Log("Planet!");
        }
        if (this.tag == "Player")//only rotate the player down into the gravity well
        {            
            Quaternion targetRotation = Quaternion.FromToRotation(transform.up, direction) * transform.rotation;
            transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, RotationStrength * Time.deltaTime);
        }

        rbToAttract.AddForce(force);        
    }    
}

Я пробовал несколько способов выделения того, какой pl anet в настоящее время наиболее близок, но я не могу понять это правильно, и я не уверен, почему кватернион всегда будет указывать на то же тело, что и

...