纳金网

标题: 让摄像机跟随主角移动的几种方法 [打印本页]

作者: 烟雨    时间: 2015-8-30 00:43
标题: 让摄像机跟随主角移动的几种方法

第一 ,让摄像机作为主角的子物体,然后设置好摄像机的位置就OK了。

第二, 给摄像机拖脚本。就像噩梦射手里面的那样,摄像机俯视整个场景,然后就会跟随主角移动,但是不会旋转。
代码如下:
using UnityEngine;
using System.Collections;

public class CameraFollow : MonoBehaviour {
        public Transform target ;
        Vector3 offset ;
        public float smooth = 5.0f;
        // Use this for initialization
        void Start () {
                offset = transform.position - gameObject.transform.position;
        }
       
        // Update is called once per frame
        void FixedUpdate () {
                Vector3 targetCamPos = target.position + offset;
                transform.position = Vector3.Lerp (transform.position,targetCamPos,smooth *Time.deltaTime);
        }
}

第三 ,在主角的脚本中写如下代码(非原创)。
Transform m_Camtransform ;
        Vector3 m_CamRot ; //摄像机旋转角度
        public float height = 1.0f;
Vector3 pos = transform.position;
                pos.y += height;
                m_Camtransform.position = pos;
                // 设置摄像机的旋转方向和主角的一致。
                m_Camtransform.rotation = m_transform.rotation;
                m_CamRot = m_Camtransform.eulerAngles;
                // 锁定鼠标
                Screen.lockCursor = true ;
// x旋转摄像机
                m_CamRot.x -= rv;
                m_CamRot.y += rh;
                m_Camtransform.eulerAngles = m_CamRot;
                // 使主角的面向与摄像机一致
                Vector3 camrot = m_Camtransform.eulerAngles;
                camrot.x = 0; camrot.z = 0;
                m_transform.eulerAngles = camrot;
        // 摄像机的位置和主角的一致
                Vector3 pos = m_transform.position;
                pos.y += height;
                m_Camtransform.position = pos;





欢迎光临 纳金网 (http://go.narkii.com/club/) Powered by Discuz! X2.5