fixelのブログ

Unity&C#初心者がイチからRTSを作るまでを書き記す日記

2回目・クリックした位置にプレイヤーを移動させる

    private NavMeshPath path;
    public NavMeshAgent agent;
    public RaycastHit hit;
    public bool once = false;
    public bool targetF = false;
 

     if (Input.GetMouseButtonDown (0)) {

            if (Physics.Raycast (Camera.main.ScreenPointToRay (Input.mousePosition), out hit100)) {
                if (hit.collider.isTrigger) {//only player&enemy have isTrigger.
                    agent.destination = new Vector3(hit.transform.position.x0hit.transform.position.z);
                    targetF = true;
                } else {
                    agent.destination = hit.point;
                    targetF = false;
                }
                once = true;
            }

どういうことをやっているかというと、

agent.destination = new Vector3(hit.transform.position.x0hit.transform.position.z);

敵キャラにクリックした場合は、敵の位置に向かって移動する。

agent.destination = hit.point;

地面をクリックした場合は、クリックした場所に向かって移動する。

ということをしている。

地面はcollider.isTriggerをOFFにし、敵やプレイヤーはONにすることで区別しています。

 

もしもこの条件分岐がなく、「agent.destination = hit.point;」だけにした場合は、

敵にクリックした時、そのクリックした位置(側面)のy座標を0にしたポイントがdestinationに設定されるため、

敵に向かって移動、ということにはなりません。

 

試しにagent.destination = hit.point;」だけにしてプレイヤーをクリックすると、停止するのではなく移動してしまうのがわかるかと思います。

 

そういうわけでこんな感じのコードになりました。