Unity游戏开发第三人称摄像机跟随

  在第三人称游戏开发中,因为我们的人物是会不断移动的,所以我们的相机需要保持合适的角度跟随我们的人物进行移动,最简单的一种实现方法是先在unity场景中将摄像机调整到合适的位置,然后将它放到我们的人物下面,让他成为人物的子物体,这样做也可以达到摄像机跟随的目的。如果对摄像机跟随的要求不高的话可以临时采用这种方法

  为了实现第三人称摄像机跟随的功能,大部分情况先我们都是采用编写代码的方法来实现的。下面是本人实现的一种摄像机跟随的方法,仅供参考,实现的功能是按住键盘AD键可以让摄像机视野围绕人物左右移动,按住键盘ws键可以让摄像机视野围绕人物上下移动,滑动鼠标滚轮能够实现视野的拉近远离功能。如图我创建了几层空物体空物体leftandright-->Upanddown-->zoomconter-->conter,摄像机放在conter下面,我们知道在Unity中如果存在父子级关系,子物体会跟随父物体进行运动的,所以我用代码分别对leftandright-->Upanddown-->zoomconter进行旋转控制,也就实现了对其子物体摄像机的控制(操作时要首先摆好层级的相对位置leftandright始终与人物坐标保持一致),脚本如下是挂在leftangright上的,采用的是单例模式

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
    //1,知道自己要做什么
    //2,用什么API可以实现功能
    //3,写出来,验证,改错
public class CamerControl : MonoBehaviour {

    public static CamerControl instance;
    void Awake()
    {
        instance = this;
    }
    [SerializeField]
    private Transform Upanddown;
    [SerializeField]
    private Transform Zoomconter;
    [SerializeField]
    private Transform conter;

    //控制视野左右移动的方法
    public void SetRotate(int type)
    {
        transform.Rotate(0,Time.deltaTime*(type==1?1:-1)*30,0);
      
    }
    //控制视野上下移动的方法
    public void SetUp(int type)
    {
        Upanddown.Rotate(0,0,Time.deltaTime*(type==1?1:-1)*30);
        //Upanddown.transform.localEulerAngles = new Vector3(0, 0, Mathf.Clamp(Upanddown.transform.localEulerAngles.z,-90f,0f));
    }
    //控制视野远近的方法
    public void SetScale(int type)
    {
        conter.Translate(Vector3.forward*(type==1?1:-1));
    }
}

  之后在人物控制脚本的Update函数中调用CameraFllow函数

//控制摄像机移动的方法
    void CameraFllow()
    {
        if (CamerControl.instance == null) return;
        CamerControl.instance.transform.position = transform.position;
        if (Input.GetKey(KeyCode.A))
        {
            CamerControl.instance.SetRotate(1);
        }
        else if (Input.GetKey(KeyCode.D))
        {
            CamerControl.instance.SetRotate(-1);
        }
        if (Input.GetKey(KeyCode.W))
        {
            CamerControl.instance.SetUp(-1);
        }
        else if (Input.GetKey(KeyCode.S))
        {
            CamerControl.instance.SetUp(1);
        }
        if (Input.GetAxis("Mouse ScrollWheel")>0)
        {
            CamerControl.instance.SetScale(1);
        }
        else if (Input.GetAxis("Mouse ScrollWheel")<0)
        {
            CamerControl.instance.SetScale(-1);
        }
    }

猜你喜欢

转载自www.cnblogs.com/linkshow/p/9716070.html