我之前曾问过这个问题,但从未得到回应,我的目标是创建一个统一的2D摄像头控制器,该控制器始终沿玩家X轴填充,而在y上它将忽略玩家Y,直到他达到特定高度,然后它将跟随玩家上升,这是我的代码:
public float baseCameraHeight = 5.0f; // default y-position of camera
public float heightThreshold = 20.0f; // minimum height for camera to follow vertically
public float cameraDistance = -10.0f; // default z-position of camera
public gameobject player;
Vector3 playerPos = player.transform.position; line based on how the player
Vector3 cameraPos = new Vector3(playerPos.x, baseCameraHeight, cameraDistance);
if (playerPos.y > heightThreshold)
{
cameraPos.y += playerPos.y - heightThreshold;
}
Camera.main.transform.position = cameraPos;
此代码可以正常工作,除非玩家到达高度点时,它将跟随玩家,但它将玩家保持在屏幕的最上方,我可以寻求帮助吗?
答案 0 :(得分:0)
使用此代码:
public float heightThreshold = 20.0f; // minimum height for camera to follow vertically
public float cameraDistance = -10.0f; // default z-position of camera
public GameObject player;
public Vector3 offset;
private float currentX;
private float currentY;
void Start()
{
currentX = player.transform.position.x;
currentY = player.transform.position.y;
}
void LateUpdate()
{
currentX = player.transform.position.x;
currentY = Mathf.Lerp(currentY, player.transform.y, 0.125f);
Camera.main.transform.positoin = new Vector3(currentX, currentY, cameraDistance) + offset;
if (player.transform.position.y > Camera.main.transform.position.y + heightThreshold)
currentY = player.transform.position.y - heightThreshold;
else if (player.transform.position.y < Camera.main.transform.position.y - heightThreshold)
currentY = player.transform.position.y + heightThreshold;
}
答案 1 :(得分:0)
当您从玩家的位置移开高度阈值时,您会将相机降低高度阈值,从而使角色出现在屏幕顶部。当其高于该阈值以将播放器居中时,将相机的y位置设置为恰好与播放器的y位置。 用以下代码替换if语句中的代码:
cameraPos.y = playerPos.y;
这将可怕地发生,而无需线性插值,但应为您提供预期的结果。
更平滑的相机将使用线性插值(Google it):
void FixedUpdate()
{
cameraPos.x = playerPos.x
if (playerPos.y > heightThreshold)
{
cameraPos.y = Mathf.Lerp(cameraPos.y, playerPos.y, Time.deltaTime * speed);
//Speed should be changed by you to increase the speed the camera moves upwards.
}
else
{
cameraPos.y = MathF.Lerp(cameraPos.y, defaultCameraYValue, Time.deltaTime * speed);
//Default camera value is the Y value you want the camera to normally travel at
}
Camera.main.transform.position = cameraPos;
}