【Unity】實現角色的移動、朝向以及攝像機跟隨

實現效果

 

 1、角色移動和朝向

using UnityEngine;
using System.Collections;

public class Player : MonoBehaviour
{
    public float moveSpeed = 0.01f;      //角色移動速度
    private float h;
    private float v;
    private Vector3 dir;
    private void Update()
    {
        PlayerMove();
    }

    void PlayerMove()
    {
        h = Input.GetAxis("Horizontal");
        v = Input.GetAxis("Vertical");
        dir = new Vector3(h, 0, v);
        transform.LookAt(transform.position + dir);                 //角色朝向
        transform.Translate(dir * moveSpeed, Space.World);          //用Tranlate方法實現移動
    }
}

移動的實現方法很簡單,用Input.GetAxis接收來自鍵盤的輸入。

參數Horizontal代表水平方向,即A、D鍵,按下A\D鍵會持續返回一個0到-1/1之間的浮點數;Vertical代表垂直方向,即W、S鍵,按下W/S鍵同樣會返回0到1/-1之間的浮點數。浮點數的大小取決於多久鬆開按鍵。

Horizantal、Vertical返回值圖例

 

 將上圖的D、S、A、W假設爲東、南、西、北方向,原點是角色的位置,這樣根據變量H、V,得到角色要移動的距離和方向。

實現移動時角色的朝向,就是以角色所在位置作爲參考系,加上dir方向即可

 

2、攝像機跟隨

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

public class CameraFollow : MonoBehaviour {

    private Transform p_tranform;
    private Vector3 CameraPos;

    private void Start()
    {
        p_tranform = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
        CameraPos = transform.position - p_tranform.position;                   //攝像機與跟隨對象的距離
    }

    private void Update()
    {
        Vector3 Pos = CameraPos + p_tranform.position;
        transform.position = Vector3.Lerp(transform.position,Pos,0.05f);        //線性插值,實現攝像機跟隨時的緩動
    }


}

 攝像機實現跟隨,就是攝像機的位置 = 攝像機與跟隨對象的距離 + 跟隨對象的位置,攝像機與跟隨對象的距離是固定的,可以由攝像機位置 - 跟隨對象位置得到

Lerp方法,即線性插值,可以實現攝像機跟隨時的緩動效果

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