亡命时速游戏制作4
1.在亡命时速游戏制作3的基础上,我们发现小车在运行时容易跑到屏幕外面,我们此时就无法观察,因此我们要使相机跟随小车的运动。
我们选择主摄像机(Main Camera),将它的Position的Y和Z值分别改为40和-25,使相机也位居中央,对准我们的小车。
2.在Scripts中,新建一个C#脚本,并取名为CameraFollow(相机跟随),将其添加到主摄像机上。
3.双击CameraFollow,进入Visual Studio中进行编辑。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraFollow : MonoBehaviour{
private GameObject player; //创建一个游戏变量,作为玩家
//Use this for initialization
void Start (){
player = GameObject.FindGameObjectWithTag("Player"); //获取带有Tag(标签)为Player的游戏对象
}
//Update is called once per frame
void LateUpdate(){
if(player == null) //如果玩家为空,即在开始的时候,我们没有得到一个玩家的引用
{
player = GameObject.FindGameObjectWithTag("Player"); //获取参数
return;
}
Movement();
}
//创建运动逻辑代码
void Movement()
{
float posX = player.transform.position.x;
float posZ = player.transform.position.z-25; //因为相机跟随在小车后,我们设置距离为25
transform.position = new Vector3(posX, transform.position.y, posZ); // 设置新矢量位置
}
}
4.保存完代码后,我们回到Unity 3d中,给小车car1加上为Player的Tag,并提高车速为50。
5.完成后我们可以保存一下,然后运行,此时小车比较流畅,快速的行驶。
敬请期待:亡命时速游戏制作(五)