我是Unity的超级新手,正在通过制作我的第一个游戏来学习。我希望摄像机跟随玩家,但只能在 X 轴上。我之前曾将相机设置为玩家的孩子,但这并没有像我想要的那样工作。所以我编写了一个 C# 脚本来跟随播放器,如下所示:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class cameraFollow : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.position = new Vector3(GameObject.Find("robot_body").transform.position.x, 0f, 0f);
}
}
但是,这在运行时仅显示蓝色背景。我做错了什么吗?
通过将z
位置设置为0
,您的相机最终可能会接近所有内容以渲染它。
尽量不要用0
覆盖y
和z
,而是保留当前值:
// If possible rather already reference this via the Inspector!
[SerializeField] private GameObject robot;
private void Start()
{
// As fallback get it only ONCE
if(!robot) robot = GameObject.Find("robot_body");
}
void Update()
{
// get the current position
var position = transform.position;
// overwrite only the X component
position.x = robot.transform.position.x;
// assign the new position back
transform.position = position;
}