首页 > 解决方案 > 如何在 Unity 2D 上移动相机

问题描述

我想让相机跟随我的角色,但没有任何效果。也许我做错了。

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

public class Camera: MonoBehaviour
{
    Transform player;
    
    private void Start()
    {
        player = GameObject.Find("Player").transform;
    }
    private void FixedUpdate()
    {
        playerVector = player.position;
        playerVector.z = 10;
        transform.position = Vector3.lerp(transform.position, playerVector, Time.deltaTime);
    }
}

标签: unity3d

解决方案


这比你想象的要容易!顺便说一句,请不要忘记将我的答案标记为有用(如果是)(打勾)从这里获取代码:

//viewArea is your player and change the off position to make the player in the center of the screen as per you want. Try changing its y axis up or down, and same with the x and z axis.
[SerializeField] private Transform viewArea;
[SerializeField] Vector3 off;
// This is how smoothly your camera follows the player
[SerializeField] [Range(0, 3)]
private float smoothness = 0.175f;
private Vector3 velocity = Vector3.zero;

private void LateUpdate() {
    Vector3 desiredPosition = viewArea.position + off;
    transform.position = Vector3.SmoothDamp(transform.position, desiredPosition, ref velocity, smoothness);
}

希望它有效!


推荐阅读