簡體   English   中英

在對剛體施加力后,在 unity 2D 中,如何使其旋轉以面向行進方向

[英]In unity 2D after applying force to a rigid body how do I make it rotate to face the direction of travel

這一切都是新的。 我已經嘗試按照我在此處找到的一些示例進行操作,但似乎都沒有用。 我現在擁有的最好的是

 rb.transform.up = rb.GetComponent<Rigidbody2D>().velocity.normalized;

但這會使剛體立即旋轉到新的行進方向。 有沒有辦法讓它旋轉得更慢而不是在一幀中跳到新的行進方向?

任何幫助,將不勝感激:)

這是我用來施加力的代碼,如果重要的話? 我是從一個教程中得到的,該教程基於拖動鼠標來施加力

public class DragNShoot : MonoBehaviour
{
    public float power = 10f;
    public Rigidbody2D rb;

    
    
    public Vector2 minPower;
    public Vector2 maxPower;

    public TrajectoryLine tl;

    Camera cam;

    Vector2 force;
    Vector3 startPoint;
    Vector3 endPoint;

    public void Start()
    {
        cam = Camera.main;
        tl = GetComponent<TrajectoryLine>();
    }

    public void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            startPoint = cam.ScreenToWorldPoint(Input.mousePosition);
            startPoint.z = 15;
            
        }

        if (Input.GetMouseButton(0))
        {
            Vector3 currentPoint = cam.ScreenToWorldPoint(Input.mousePosition);
            currentPoint.z = 15;
            tl.RenderLine(startPoint, currentPoint);
        }

       if (Input.GetMouseButtonUp(0))
        {
            endPoint = cam.ScreenToWorldPoint(Input.mousePosition);
            endPoint.z = 15;

            force = new Vector2(Mathf.Clamp(startPoint.x - endPoint.x, minPower.x, maxPower.x), Mathf.Clamp(startPoint.y - endPoint.y, minPower.y, maxPower.y));
            rb.AddForce(force * power, ForceMode2D.Impulse);
            tl.EndLine();
        }

        
    }

}

這是輪換的腳本

public class FaceDirectionOfTravel : MonoBehaviour
{
   
    public Rigidbody2D rb;

   

    // Update is called once per frame
    void Update()
    {
        rb.transform.up = rb.GetComponent<Rigidbody2D>().velocity.normalized;
    }
}

如您所見,我剛剛獲取了速度並將其應用於旋轉,我猜這只是立即更改它以匹配,但我希望它明顯旋轉以匹配旋轉。 我已經嘗試了一些我在這里看到的 Slerp 示例,但似乎只是讓它自由旋轉。我一定是遺漏了一些非常明顯的東西,所以我想在這里問一下。 謝謝。

編輯:所以我已經找到了一種方法來讓它工作,方法是在我希望旋轉的 object 之上創建另一個 object 並使用 Slerp 旋轉頂部的 object 以緩慢旋轉到與原始 object 相同的位置由於施加力而立即捕捉代碼很簡單

public class RotateSprite : MonoBehaviour
{
    [SerializeField] private Rigidbody2D rbOfTarget;
    [SerializeField] private Rigidbody2D rb;

  

    private void Start()
    {
       
    }

    // Update is called once per frame
    void Update()
    {

        rb.transform.position = rbOfTarget.transform.position;

        rb.transform.rotation = Quaternion.Slerp(rb.transform.rotation, rbOfTarget.transform.rotation, 30* Time.deltaTime);
        

    }
}

如果有人知道更好的解決方案,請告訴我。 謝謝。

你的游戲是3D還是2D的? 你一直說它是二維的,但標簽上說它是 3D,如果是二維的,你就不需要 Z position。如果它在 3D 中,你就必須將 rigidbody2D 更改為剛體。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM