0
  • シーンに「 Player 」というオブジェクトがあります。
  • 「 Trees 」と呼ばれる複数のオブジェクトもあります。

ここで、ユーザーが「ツリー」をクリックするたびに、「プレーヤー」がゆっくりとその位置に移動するようにしたいと考えています (Lerp または moveTowards を使用)。


このコードには 2 つの問題があります。

このコードを汎用にしたい

木のオブジェクトをクリックするたびに、プレーヤーをそのに向かって移動させたいと思います。このスクリプトを作成して、各ツリー オブジェクトにアタッチしたくありません。

  • スクリプトはどこに置くべきですか?

    現在、このコードをすべてのツリー オブジェクトに添付しています。

  • シーン内のすべての木のオブジェクトに適用するには、どのように書き留めればよいですか?

移動中にもう一度クリックすると、前の移動をキャンセルして新しい位置への移動を開始します

  • プレイヤーがクリックされた別のオブジェクトに向かって移動しているときに別のオブジェクトをクリックすると、プレイヤーは以前の位置への移動を停止し、新しいポイントへの移動を開始するようにするにはどうすればよいですか 。

新しい UnityScript に順応するのに苦労しています。私は厳密にJavascriptのバックグラウンドから来ており、そのうちの2つは非常に異なるセマンティクスを持つ言語のようです。したがって、誰かがコードでこれに答えた場合(これは私が望むものです:))、詳細なコメントもいただければ幸いです。


私は現在これを行います:

var playerIsMoving = false;
Public playerObject: Gameobject; //I drag in the editor the player in this public var

function update(){  

   var thisTreePosition = transform.point; //this store the X pos of the tree
   var playerPosition = player.transform.point;

   if(playerIsMoving){
    player.transform.position = Vector2.MoveTowards(playerPosition, thisTreePosition, step);
   }

}

function OnMouseDown(){
    playerIsMoving = true;
}

私は Unity を持っていない自宅からこれを書いており、コードの構文を忘れていたので、上記のコードにはタイプミスや問題があると予想されます

4

2 に答える 2

3

プレーヤーにモーションスクリプトを入れることをお勧めします。Raycast を使って木にぶつかったかどうかをテストするにはどうすればよいでしょうか。

http://docs.unity3d.com/ScriptReference/Physics.Raycast.html

Vector3 positionToWalkTo = new Vector3();

void Update() {
        if (Input.GetMouseButtonDown(0)) {
            RaycastHit hit;
            Ray ray = new Ray(transform.position, direction);

            if (Physics.Raycast(ray, out hit))
               if (hit.gameObject.tag.Equals("tree")){
                  positionToWalkTo = hit.gameObject.transform.position;
               }

        }

        float step = speed * Time.deltaTime;
        transform.position = Vector3.MoveTowards(transform.position, positionToWalkTo, step);
    }

このようなものを実行するには、すべての木にタグを付ける必要があります。

「ジャバスクリプト」

var target: Transform;
// Speed in units per sec.
var speed: float;

function Update () {

        if (Input.GetMouseButtonDown(0)) {
             var hit: RaycastHit;
             var ray = Camera.main.ScreenPointToRay (Input.mousePosition);

        // Raycasting is like shooting something into the given direction (ray) and hit is the object which got hit
        if (Physics.Raycast(ray, hit)) {
            if (hit.gameObject.tag = "tree")
                target = hit.gameObject.transform.position;  // Sets the new target position
        }
    }

    // The step size is equal to speed times frame time.
    var step = speed * Time.deltaTime;

    // Move our position a step closer to the target.
    transform.position = Vector3.MoveTowards(transform.position, target.position, step);
}
于 2015-01-18T17:14:58.133 に答える