unity模型實現鼠標點擊引導運動

一,鼠標引導模型運動:

在模型的Inspector面板上,點擊Add Component,添加導航組件Nav Mesh Agent組件:

設置Radius和Height兩個參數,畫出物體大概範圍:

 

 Project面板上創建腳本MouseClick,並拖到斑馬模型的Inspector面板上:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

public class MouseClick : MonoBehaviour {


    public NavMeshAgent agent;//得到模型的NavMeshAgent
    public Animator anim;


    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);//把鼠標座標轉化爲射線
            RaycastHit hit;//碰撞信息
            if (Physics.Raycast(ray, out hit))//如果發生碰撞
            {
                agent.SetDestination(hit.point);//將鼠標點擊位置,設置爲agent的位置,也就是模型的位置
            }
        }

        anim.SetFloat("speed", agent.velocity.magnitude);
    }
}

將Nav Mesh Agent拖拽到Mouse Click腳本的Agent處:

Nav Mesh Agent的Angular Speed設置大一點,可以讓物體移動更加靈活: 

二,控制視野——攝像機跟隨:

調整模型和攝像機的位置,在遊戲Game畫面上,顯示合適的視野。 

創建腳本,並託給攝像機:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FollowTarget : MonoBehaviour {

    public Transform hero; //跟隨目標
    private Vector3 offset; //位置偏移量
	// Use this for initialization
	void Start () {
        offset = transform.position - hero.position;//設定的偏移量=當前位置-模型位置
	}
	
	// Update is called once per frame
	void Update () {
        transform.position = offset + hero.position;//設定的偏移量+模型位置
	}
}

將模型,拖拽到腳本這裏:

三,讓模型動起來:

在Project面板上,創建動畫狀態機Animator Controller,命名爲BMController.

 選中斑馬模型,在Inspector面板上,將剛剛創建的BMController,拖過去:

選中斑馬模型,從window菜單欄找到Animator,並將需要的動畫拖動到上面。

右擊動畫選中Make Transition,來建立聯繫:

 我們通過速度來進行切換,從靜止到慢走到快跑

創建speed:

選中兩個動畫中的一條線: 

 

在Inspector面板上:

1:

表示速度大於0時,切換到Trot,慢走動畫。

2:

 

 

3:

 

4:

 

 

選中斑馬模型,在Inspector面板上,將Animator拖到 如圖所示位置:

 

運行試試! 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章