我们使用Unity 3D实现一个简单的超车小游戏。
开发环境:Unity5.0.2以上。
运行效果:
玩家必须在有限时间内进入通关大门才能获得胜利,游戏过程中,玩家可以加速,可以左右移动躲避汽车,图中碰到任何一辆车,或者规定的时间进入通关大门。
关键功能及脚本:
控制玩家左右移动:
public class PlayerScript : MonoBehaviour {
private float speed_L_R = 0.1F; //玩家左右移动的速度;
private float speed_F = 0.1F; //玩家向前的速度;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetKey (KeyCode.W) ) //按下A键翔左运动
transform.Translate (-Vector3.forward * speed_F);
if (Input.GetKey (KeyCode.A) ) //按下A键翔左运动
transform.Translate (-Vector3.left * speed_L_R);
if (Input.GetKey (KeyCode.D)) //按下D键向右运动
transform.Translate (-Vector3.right * speed_L_R);
}
}
摄像机与玩家匹配:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MyCameraScript : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Transform caTransform;
//获取玩家的世界坐标值
caTransform = GameObject.Find ("player").GetComponent<Transform> ();
//摄像机的x值设为3
float Camera_X = 3.0f;
//摄像机的y值设定
float Camera_Y = caTransform.position.y + 1.5f;
//摄像机的z值设定
float Camera_Z = caTransform.position.z - 5.0f;
//重置摄像机的位置,使摄像机永远跟随玩家运动
transform.position = new Vector3 (Camera_X, Camera_Y, Camera_Z);
}
}
当我们一直往左或者一直往右移动玩家时,就会离开摄像机的视角范围。我们编写脚本使之移动到公路边缘时,便
不能继续移动。
if (Input.GetKey (KeyCode.A) && transform.position.x > -0.7) //按下A键翔左运动
transform.Translate (-Vector3.left * speed_L_R);
if (Input.GetKey (KeyCode.D) && transform.position.x < 6.8) //按下D键向右运动
transform.Translate (-Vector3.right * speed_L_R);
汽车的随机出现,我们这里有两种汽车,需要让这两种车随机分布并出现在场景中,并且可以向前行驶。需要作为刚体并加上盒子碰撞。:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MyPreScript : MonoBehaviour {
public int car_