簡體   English   中英

我想讓y軸上的對象沿Z軸移動嗎?

[英]I want an Object lerping in the y-axis to move along the Z-Axis?

我目前正在制作不是在Unity中隨機生成的亞軍類型游戲。 播放器,相機和背景留在同一位置(夾緊了播放器的移動),並且危險通過以下簡單的代碼行沿負Z軸傳向播放器:

public float speed;

private Rigidbody rb;

void Start () {
    rb = GetComponent<Rigidbody> ();
    rb.velocity = transform.forward * -speed;
}

而且效果很好。 現在,我想添加不僅會朝向玩家的小行星,而且還會使小行星向上和向下移動(並重復),我嘗試使用Lerp()進行操作。 我不是Lerp的專業人士,因此我使用了在網上找到的有效代碼:

public Transform startPos, endPos;
public bool repeatable = true;
public float speed = 1.0f;
public float duration = 3.0f;

float startTime, totalDistance;

IEnumerator Start () {
    startTime = Time.time;

    while(repeatable) {
        yield return RepeatLerp(startPos.position, endPos.position, duration);
        yield return RepeatLerp(endPos.position, startPos.position, duration);
    }
}

void Update () {
    totalDistance = Vector3.Distance(startPos.position, endPos.position);
    if(!repeatable) {
        float currentDuration = (Time.time - startTime) * speed;
        float journeyFraction = currentDuration / totalDistance;
        this.transform.position = Vector3.Lerp(startPos.position, endPos.position, journeyFraction);
    }
}

public IEnumerator RepeatLerp(Vector3 a, Vector3 b, float time) {
    float i = 0.0f;
    float rate = (1.0f / time) * speed;
    while (i < 1.0f) {
        i += Time.deltaTime * rate;
        this.transform.position = Vector3.Lerp(a, b, i);
        yield return null;
    }
}

我要做的是為起點和終點位置創建2個空對象,然后將危險和兩個危險點放在另一個空對象下,我們將其稱為“父對象”(因此,父對象>-危險-開始-結束)。 然后,我將沿Z軸移動的腳本添加到了父級空白中,這有點奏效,但就像跳躍一樣。 因此,拉幅有效,但直到完成拉幅功能,對象才沿Z軸移動,對象跳到Z軸的新位置。 因此,它看起來非常跳躍和小故障。

我該怎么做才能使沿Z軸的平滑運動以及lerp沿Y軸仍然有效?

謝謝!!

PS:我知道我可以移動角色和照相機等,但是現在我想保持這種方式。

協程的RepeatLerp在多個幀上起作用,但是接收到Vector3類型的輸入。 參考點的實際位置將隨時間變化,但是參數值ab直到協程終止之前都不會變化。

因此, 直接的解決方案很簡單:無需傳遞Vector3 ,而是傳遞對Transform引用,並在每幀中獲取其新位置。 將功能更改為此:

public IEnumerator RepeatLerp(Transform a, Transform b, float time)
{
    float i = 0.0f;
    float rate = (1.0f / time) * speed;
    while (i < 1.0f)
    {
        i += Time.deltaTime * rate;
        this.transform.position = Vector3.Lerp(a.position, b.position, i);
        yield return null;
    }
}

在“ Start功能中,調用現在為:

yield return RepeatLerp(startPos, endPos, duration);
yield return RepeatLerp(endPos, startPos, duration);

但這將解決您的問題,但是, 我已經強烈建議您重新考慮移動對象的方式 您將Rigidbody語義與使用transform移動對象混合使用,這是一種非常糟糕的做法。 該引擎並非旨在這樣做,將來可能會導致性能問題。

通常,如果您的對象上有碰撞器(看起來像是有碰撞器),則應僅使用Rigidbody並對其施加速度/力來移動對象。 如果您想使用Lerp ,可以看一下Rigidbody.MovePosition ,但最好使用Rigidbody.velocity ,例如(以下代碼僅是示意圖):

if (transform.position.x > highLimit) rigidbody.velocity -= 2*pulsingSpeed;
if (transform.position.x < lowLimit) rigidbody.velocity += 2*pulsingSpeed;

暫無
暫無

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

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