7.让摄像机随角色移动
现在,角色可以跳跃到云朵上了,但当角色跳到画面顶部再往上跳的时候,摄像机就看不到角色了。所以,要让摄像机随角色的移动而移动。
摄像机也是一种游戏对象,可以像其他对象一样使用控制器脚本来控制它的位置。
7.1创建摄像机控制器
在工程窗口中右击选择 Create -> C# Script,将文件名改为 CameraController。编写脚本如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraController : MonoBehaviour
{
GameObject player;
// Start is called before the first frame update
void Start()
{
player = GameObject.Find("cat");
}
// Update is called once per frame
void Update()
{
Vector3 playerPos = player.transform.position;
// 移动摄像机
if (Mathf.Abs(transform.position.y - playerPos.y) > 5.0f || Mathf.Abs(transform.position.x - playerPos.x) > 1.5f)
transform.position = new Vector3(playerPos.x, playerPos.y, transform.position.z);
}
}
在上面的代码中,通过检查摄像机位置与角色位置的差距,当超过一定范围时,我们就认为在画面中看不到了,从而改变摄像机位置。
将脚本挂载到 Main Camera 对象。
启动游戏,检查效果。最终效果如下图所示:
版权声明:本文图片和内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送联系客服 举报,一经查实,本站将立刻删除,请注明出处:https://www.4kpp.com/78169.html