查看: 2013|回复: 0
打印 上一主题 下一主题

[其他] 让摄像机跟随主角移动的几种方法

[复制链接]

9903

主题

126

听众

7万

积分

首席设计师

Rank: 8Rank: 8

纳金币
53488
精华
316

最佳新人 热心会员 灌水之王 活跃会员 突出贡献 荣誉管理 论坛元老

跳转到指定楼层
楼主
发表于 2015-8-30 00:43:38 |只看该作者 |倒序浏览

第一 ,让摄像机作为主角的子物体,然后设置好摄像机的位置就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;
分享到: QQ好友和群QQ好友和群 腾讯微博腾讯微博 腾讯朋友腾讯朋友 微信微信
转播转播0 分享淘帖0 收藏收藏0 支持支持0 反对反对0
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

手机版|纳金网 ( 闽ICP备2021016425号-2/3

GMT+8, 2025-8-13 02:25 , Processed in 0.069954 second(s), 29 queries .

Powered by Discuz!-创意设计 X2.5

© 2008-2019 Narkii Inc.

回顶部