using UnityEngine;
using System.Collections;
public class CameraController : MonoBehaviour
{
public GameObject player; //Public variable to store a reference to the player game object
private Vector3 offset; //Private variable to store the offset distance between the player and camera
// Use this for initialization
void Start()
{
//Calculate and store the offset value by getting the distance between the player's position and camera's position.
offset = transform.position - player.transform.position;
}
// LateUpdate is called after Update each frame
void LateUpdate()
{
// Set the position of the camera's transform to be the same as the player's, but offset by the calculated offset distance.
transform.position = player.transform.position + offset;
transform.LookAt(player.transform);
}
}
如果我只使用这一行:
transform.LookAt(player.transform);
它将根据播放器的移动旋转相机,但相机将保持原位。 当我也在使用这条线时:
transform.position = player.transform.position + offset;
相机会移动,但现在它将位于播放器前面而不是跟在它后面。我希望相机能够LookAt并从后面跟随。
答案 0 :(得分:1)
您应该在玩家的本地空间中获得偏移量。您可以使用矢量数学(例如,player.transform.position - player.transform.forward * distance
),也可以在播放器的层次结构中使用引用空GameObject作为相机的位置目标。
答案 1 :(得分:0)
你的脚本是正确的;要使相机跟随玩家,你必须:
创建空游戏对象时,不要忘记将其位置重置为0,0,0。
我希望这会有所帮助。
答案 2 :(得分:0)
检查此脚本,它将以摄像机的永久视点矢量跟随目标,然后,如果您想跟踪目标的前向矢量,则需要在脚本中添加其他逻辑:)
public class CameraFollowController : MonoBehaviour
{
public GameObject target;
int offsetDistance = 10;
int offsetHeight = 5;
Vector3 targetLookAtVec;
void Start()
{
Camera.main.transform.position = target.transform.position
- target.transform.forward * offsetDistance
+ target.transform.up * offsetHeight;
Camera.main.transform.LookAt(target.transform);
targetLookAtVec = Camera.main.transform.position - target.transform.position;
}
void LateUpdate()
{
Camera.main.transform.position = target.transform.position + targetLookAtVec;
}
}