簡體   English   中英

游戲對象來回旋轉

[英]GameObject rotate back and forth

我正在為我的游戲制作一些草,它需要看起來像有風。 所以我試圖寫一個腳本,但根本沒有成功。 腳本將類似於它旋轉一點的地方,然后是另一種方式。 只是來回。

public GameObject grass;

    private void FixedUpdate()
    {
        grass.transform.Rotate(transform.rotation.x, transform.rotation.y, 90f * Time.deltaTime, Space.Self);
    }

正如您在我的代碼中看到的那樣,它將永遠圍繞自身旋轉。 這就是我得到的。

我從來沒有用 Unity 做過什么,但你可以試試這樣的東西。

如果你想要一個漂亮的波浪效果,你應該使用Math.Sin() 也許是這樣的:

public GameObject grass;
private double _time;

    private void FixedUpdate()
    {
        _time = _time + Time.deltaTime;

        // I assumed that the angle for unity is in degrees.
        // Math.Sin work with Radians. a full wave will take about 6 seconds.
        // It will go between 0 and 90 degrees.
        var angle = (float)(45 + (45 * Math.Sin(_time))); 

        grass.transform.Rotate(transform.rotation.x, transform.rotation.y, angle, Space.Self);
    }

如果您希望旋轉從 -45 度到 45 度,請使用: (float)(45 * Math.Sin(_time));

首先,您不想在FixedUpdate執行此操作,而是在Update執行此操作,否則您會感到緊張不安。

然后你可以簡單地定義你的兩個目標旋轉並使用Mathf.PingPong作為Quaternion.Slerp中的因子,以便在兩個旋轉之間來回插值:

public Vector3 eulerAngles1;
public Vector3 eulerAngles2;
// How long it takes to go from eulerAngles1 to eulerAngles2
public float duration;

Quaternion rotation1;
Quaternion rotation2;

private void Start()
{
    rotation1 = Quaternion.Euler(eulerAngles1);
    rotation2 = Quaternion.Euler(eulerAngles2);
}

private void Update()
{
    var factor = Marhf.PingPong(Time.time / duration, 1);
    // Optionally you can even add some ease-in and -out
    factor = Mathf.SmoothStep(0, 1, factor);

    // Now interpolate between the two rotations on the current factor
    transform.rotation = Qiaternion.Slerp(rotation1, rotation2, factor);
}

暫無
暫無

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

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