2016-07-10 7 views
0

私の問題は、ある速度で特定のラウンド範囲内でオブジェクトがランダムに動くようにすることです。 今は非常に速く動いていて、それを速度で掛けても動作しません。あなたはすべてのアップデートで新しい乱数を作っているので、だ円内のランダムな動き

using UnityEngine; 
using System.Collections; 

public class RandomTargetMovement : MonoBehaviour { 
    public float radius = 20.0f; 

    void Update(){ 
     transform.position = Random.insideUnitCircle * radius; 
    } 
} 
+0

あなたのランダムは毎回異なります(私は推測しています)ので、ランダムな開始位置を設定し、円内を移動させる角速度を割り当てる方がよいでしょうか? –

+0

または円内のランダムなターゲットをピックアップして徐々にその方向に向かって移動し、再度新しいランダムなターゲットを選択してください – mgear

+0

https://unisalesianogames.files.wordpress.com/2011/08/programming-game-ai-by-example-mat- buckland2.pdfは操縦行動に関する非常に良い本です。第3章は私を助けました。 –

答えて

0

は、ここに私のコードです。これはいくつかの理由で悪いことです。

しかし、この特定の例では、悪いだけでなく、単に機能しません。これは、フレームがレンダリングされるたびに更新が呼び出されるため、スピードをどのように設定していても、常に動きがぎくしゃくすることになります。そのためには、deltaTimeを使用する必要があります。

オブジェクトがポイントに移動するのは、です。次に、は新しいランダムな点に向かって動き始めます。ここではあまりにもエレガントなソリューションです:

using UnityEngine; 
using System.Collections; 

public class TestSample : MonoBehaviour { 

    public float radius = 40.0f; 
    public float speed = 5.0f; 

    // The point we are going around in circles 
    private Vector2 basestartpoint; 

    // Destination of our current move 
    private Vector2 destination; 

    // Start of our current move 
    private Vector2 start; 

    // Current move's progress 
    private float progress = 0.0f; 

    // Use this for initialization 
    void Start() { 
     start = transform.localPosition; 
     basestartpoint = transform.localPosition; 
     progress = 0.0f; 

     PickNewRandomDestination(); 
    } 

    // Update is called once per frame 
    void Update() { 
     bool reached = false; 

     // Update our progress to our destination 
     progress += speed * Time.deltaTime; 

     // Check for the case when we overshoot or reach our destination 
     if (progress >= 1.0f) 
     { 
      progress = 1.0f; 
      reached = true; 
     } 

     // Update out position based on our start postion, destination and progress. 
     transform.localPosition = (destination * progress) + start * (1 - progress); 

     // If we have reached the destination, set it as the new start and pick a new random point. Reset the progress 
     if (reached) 
     { 
      start = destination; 
      PickNewRandomDestination(); 
      progress = 0.0f; 
     } 
    } 

    void PickNewRandomDestination() 
    { 
     // We add basestartpoint to the mix so that is doesn't go around a circle in the middle of the scene. 
     destination = Random.insideUnitCircle * radius + basestartpoint; 
    } 
} 

これは役立ちます。

関連する問題