Unity_如何使相机视角一直跟随角色移动

这篇博客介绍了在Unity中实现相机视角始终跟随角色移动的方法。通过修改代码`player = GameObject.FindGameObjectWithTag("Player").transform;`,将Tag由'Player'替换为实际角色的Tag,如'dog',并将脚本附加到Camera上,即可达成目标。

实例代码如下:

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

//相机视角跟踪
public class FollowTarget : MonoBehaviour {

    //游戏人物 的位置
    private Transform player;

    //游戏人物与 相机的差
    private Vector3 offset;

    //相机的速度
    private float smoothing = 3;

	// Use this for initialization
	void Start () {
        player = GameObject.FindGameObjectWithTag("Player").transform;
        offset = transform.position - player.position;
    }


    // Update is called once per frame
    void LateUpdate() {
        //player.TransformDirection(offset)
        //世界坐标转换为局部坐标
        Vector3 targetPosition = player.position + player.TransformDirection(offset);
        //Vector3.Lerp 计算相机位置 和 目标位置的插值
        transform.position = Vector3.Lerp(transform.position,targetPosition,Time.deltaTime * smoothing);
        //相机的目标看向 游戏人物
        transform.LookAt(player.position);
	}
}

根据的你的情况

只需要修

### 实现Unity2D中相机跟随角色移动 为了使相机能够平滑地跟随角色,在Unity2D项目中通常会采用`Vector3.Lerp`或更推荐使用的`Vector3.SmoothDamp`函数来创建这种效果[^4]。下面是一个具体的实现方案: #### 创建脚本并附加到主摄像机上 编写C#脚本来管理相机的行为,并将其挂载至场景中的Main Camera对象。 ```csharp using UnityEngine; public class SmoothFollow : MonoBehaviour { public Transform target; // 跟随的目标,即玩家角色 public float smoothSpeed = 0.125f; public Vector3 offset; private void LateUpdate() { if (target) { Vector3 desiredPosition = target.position + offset; Vector3 smoothedPosition = Vector3.SmoothDamp(transform.position, desiredPosition, ref velocity, smoothSpeed); transform.position = smoothedPosition; } } private Vector3 velocity = Vector3.zero; } ``` 此段代码定义了一个名为`SmoothFollow`的类,该类继承自MonoBehaviour。通过调整公共变量`smoothSpeed`可改变跟随时的速度和平滑度;`offset`用于设定相对于目标位置偏移量,以便于更好地构图显示整个游戏画面。 #### 设置参数 - 将上述脚本保存为`SmoothFollow.cs`文件后拖拽到Hierarchy窗口下的Camera GameObject。 - 在Inspector面板内为目标(Target)字段分配要跟踪的游戏对象(通常是主角)。 - 可选地调整Offset数值以适应不同视角需求以及Smooth Speed值优化追踪流畅性。 这样就完成了基本的2D相机跟随功能设置。随着玩家操控的角色在屏幕上移动相机会自动保持一定的距离和角度追随其身后,从而营造出更加自然舒适的视觉体验。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值