2016-11-29 52 views
0

我想讓我的對象向上移動,但以隨機曲折方向移動。我已經使用下面的代碼來讓我的對象向上移動。將對象向上移動但以隨機最小值最大值

transform.position + = transform.up * playerspeed * Time.deltaTime;

但是,我該如何去使這個物體向上移動,但是以我自己的最小值和最大值的曲折方向。當它重新生成鋸齒形的路徑是隨機的?

+0

你能畫出你想要實現的路徑的形象?你只是試圖增加橫向運動的對象,兩個值之間的振盪? Z字形的每一步都是隨機的長度?每個線段的角度應該相同還是可以變化? (再次,視覺輔助可能會隱含地回答所有這些。) – Serlite

回答

1

所有你需要做的就是選擇一個x位置,然後在你向上移動時移動它。然後當你到達它時,重複這個過程。

嘗試了這一點:

private float minBoundaryX = -3f; 
private float maxBoundaryX = 3f; 
private float targetX; 
private float horSpeed = 3f; 
private float vertSpeed = 2f; 

//Pick a random position within our boundaries 
private void RollTargetX() 
{ 
    targetX = Random.Range(minBoundaryX, maxBoundaryX); 
} 

//Calculate the distance between the object and the x position we picked 
private float GetDistanceToTargetX() 
{ 
    return Mathf.Abs(targetX - transform.position.x); 
} 

private void Update() 
{ 
    //Roll a new target x if the distance between the player and the target is small enough 
    if (GetDistanceToTargetX() < 0.1f) 
     RollTargetX(); 
    //Get the direction (-1 or 1, left or right) to the target x position 
    float xDirection = Mathf.Sign(targetX - transform.position.x); 
    //Calculate the amount to move towards the x position 
    float xMovement = xDirection * Mathf.Min(horSpeed * Time.deltaTime, GetDistanceToTargetX()); 
    transform.position += new Vector3(xMovement, vertSpeed * Time.deltaTime); 
}