unity 镜头跟踪对象

镜头跟随角色顺滑移动

  

//设计内容:

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

public class CameraFollow : MonoBehaviour {

    public Transform m_TargetTransform; // 镜头要跟踪的目标
    private float depth = -18f;          // 镜头相对于角色的前后位置,负数代表位于角色后方;
    private float height = 40f;          // 镜头相对于角色的上方高度;

    [SerializeField]
    private float m_Speed = 12f; // 控制镜头跟踪时的速度,用于调整镜头额平滑移动,如果速度过大,极限情况下直接把目标位置赋给镜头,那么对于闪现一类的角色瞬移效果,将会带来不利的视觉影像


    void Update()
    {

        if (m_TargetTransform != null)
        {
            var targetposition = m_TargetTransform.position + new Vector3(0, height, depth); 
            transform.position = Vector3.MoveTowards(transform.position, targetposition, m_Speed * Time.deltaTime);
        }

    }

    public void SetTarget(Transform target)
    {

        m_TargetTransform = target;
    }
}

### Unity 中的摄像机开发教程 在 Unity 开发中,摄像机(Camera)是一个非常重要的组件,它决定了玩家如何观察游戏场景中的对象和事件。以下是关于 Unity 摄像机开发的一些核心概念和技术要: #### 1. 基本设置 新建项目后,默认会有一个 `Main Camera` 和一个光源 (`Directional Light`)。如果这些默认对象不再需要,可以直接删除它们,并按照需求重新创建一个新的摄像机[^4]。 ```csharp // 创建新的摄像机实例 public GameObject CreateNewCamera() { var newCamera = Instantiate(Resources.Load<GameObject>("Prefabs/NewCamera")); return newCamera; } ``` #### 2. 调整摄像机位置与方向 调整摄像机的位置可以通过修改其 Transform 组件来实现。这包括 Position、Rotation 和 Scale 属性。通常情况下,开发者会在 Inspector 面板手动调整这些属性,或者通过脚本来动态控制摄像机的行为[^4]。 ```csharp // 动态改变摄像机位置 void UpdateCameraPosition(Camera mainCamera, Vector3 newPosition) { mainCamera.transform.position = newPosition; } ``` #### 3. 设置正交投影 vs 透视投影 Unity摄像机支持两种主要类型的投影模式:正交投影(Orthographic Projection)和透视投影(Perspective Projection)。对于 2D 游戏来说,推荐使用正交投影;而对于 3D 游戏,则更倾向于使用透视投影[^1]。 ```csharp // 切换摄像机投影类型 void SetProjectionType(Camera camera, bool useOrthoGraphic) { camera.projectionMatrix = useOrthoGraphic ? Matrix4x4.orthogonal : Matrix4x4.perspective; } ``` #### 4. 实现平滑跟随目标的功能 为了让摄像机能够平稳地跟踪某个特定的目标(例如角色或车辆),可以采用插值算法(Interpolation Algorithm)来计算新位置[^5]。 ```csharp // 平滑追踪逻辑 IEnumerator SmoothFollow(Transform target, float smoothTime) { while (true) { yield return null; Vector3 desiredPosition = target.position + offset; transform.position = Vector3.Lerp(transform.position, desiredPosition, Time.deltaTime * smoothTime); } } ``` #### 5. 处理缩放效果 当需要让摄像机放大或缩小视图范围时,可以调节 orthographicSize 或 fieldOfView 参数。这对于实现 zoom-in/out 效果特别有用[^1]。 ```csharp // 修改摄像机视野大小 void AdjustZoomLevel(Camera cam, float newSize) { if(cam.orthographic){ cam.orthographicSize = newSize; }else{ cam.fieldOfView = newSize; } } ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值