You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity 2D中如何实现相机跟随玩家角色移动

Unity相机跟随代码问题修复方案

现有代码的错误点

  • 未声明playerVector变量,代码无法正常编译
  • 类名Camera和Unity引擎自带的UnityEngine.Camera类重名,极易引发命名冲突
  • Vector3.lerp拼写错误,C#大小写敏感,正确写法为Vector3.Lerp
  • 相机跟随逻辑写在了FixedUpdate中,该方法仅用于物理逻辑更新,相机跟随应放在LateUpdate中执行,避免出现画面卡顿、不同步问题
  • 相机z轴设置为10会导致相机位于角色前方,无法拍摄到角色,Unity默认相机朝向z轴正方向,应设置为负值
  • 缺少空值校验,找不到名为Player的对象时会抛出空引用异常

修复后代码

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

// 改类名避免和系统Camera类冲突
public class CameraFollow : MonoBehaviour
{
    Transform player;
    // 可在Inspector面板调整跟随平滑度
    public float smoothSpeed = 2f;
    // 可在Inspector面板调整相机相对角色的偏移量
    public Vector3 offset = new Vector3(0, 0, -10f);
    
    private void Start()
    {
        // 找到角色对象
        GameObject playerObj = GameObject.Find("Player");
        if (playerObj != null)
        {
            player = playerObj.transform;
        }
    }

    // 所有Update执行完后执行LateUpdate,保证相机跟随时机正确
    private void LateUpdate()
    {
        if (player == null) return;
        
        Vector3 targetPosition = player.position + offset;
        transform.position = Vector3.Lerp(transform.position, targetPosition, smoothSpeed * Time.deltaTime);
    }
}

额外操作检查项

  • 确认场景中角色对象的名称完全匹配Player,大小写、前后空格都不能有差异
  • 确保上述脚本挂载到场景中的主相机对象上
  • 可以直接在Inspector面板调整offset参数修改相机相对角色的位置,调整smoothSpeed修改跟随的平滑程度

内容的提问来源于stack exchange,提问作者Владислава Черкасова

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 09:51:04