与玩家[unity]

问题描述

using System.Collections.Generic;
using UnityEngine;

public class follow_mainship : MonoBehaviour
{
    public Transform Playerposition;
    private Vector3 cameraoffset;
    // Start is called before the first frame update
    void Start()
    {
        cameraoffset = Playerposition.position - transform.position;
        
    }

    // Update is called once per frame
    void Update()
    {
        Vector3 newpos = Playerposition.position + cameraoffset;
    }
}

我正在使用此代码与播放器一起移动相机,但无法正常工作。我在“播放器位置”框中添加了我的对象。我该怎么办?

更新: 按照答案,相机跟随我的船,只要船碰到地面,相机就会向后飞一段长距离。有什么办法可以解决?

解决方法

您获取新位置的逻辑是正确的,但是在Update()函数中,您必须使用transform.position更新摄像机的位置,并假定此脚本是您已添加到场景中“摄像机”的组件

// Update is called once per frame
void Update()
{
    Vector3 newpos = Playerposition.position + cameraoffset;
    transform.position = newpos;
}

如果此脚本不在摄像机上,则需要将其作为摄像机的参考,方法是将其作为Unity检查器中的输入(在类顶部声明public Camera cam;),然后在在检查器中将摄影机对象拖到该输入上。然后,您可以在Update()中执行cam.transform.position = newpos;

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...