记录一下今天,本身的第一个小游戏完成了,心情很舒爽。很是很是简单的小游戏,下面梳理一下过程。canvas
首先建立跑道,使用cube,拉长等等。而后建立小球sphere,小球即为玩家(player,积累单词)。再添加障碍物,在分别为其上色。ide
紧接着给小球添加脚本,让其可以受玩家控制测试
1 using System.Collections; 2 using System.Collections.Generic; 3 using UnityEngine; 4 using UnityEngine.SceneManagement; 5 6 public class Player : MonoBehaviour 7 { 8 //初始速度 9 public float speed = 10; 10 //初始转弯速度 11 public float turnSpeed = 4; 12 13 // Start is called before the first frame update 14 void Start() 15 { 16 17 } 18 19 // Update is called once per frame 20 void Update() 21 { 22 //按R键重玩,场景重置 23 if (Input.GetKeyDown(KeyCode.R)){ 24 SceneManager.LoadScene(0); 25 Time.timeScale = 1; 26 //结束当前方法,防止一直掉下去 27 return; 28 } 29 30 //获取坐标 31 float x = Input.GetAxis("Horizontal"); 32 //给物体一个变化,即x轴会有一个转弯速度,y轴不变,z轴也有一个速度 33 transform.Translate(x * turnSpeed * Time.deltaTime, 0, speed * Time.deltaTime); 34 35 //判断位置,若是在范围以外,则让它有其余的运转动做 36 if (transform.position.x < -4 || transform.position.x > 4) 37 transform.Translate(0, -10 * Time.deltaTime, 0); 38 39 //若是y轴小于-20,则中止 40 if (transform.position.y < -20) 41 Time.timeScale = 0; 42 43 44 } 45 }
给小球添加刚体组件rigidbody,使其与障碍物barrier发生碰撞,也要给障碍物添加触发器trigger,建立barrier脚本spa
1 using System.Collections; 2 using System.Collections.Generic; 3 using UnityEngine; 4 5 public class Barrier : MonoBehaviour 6 { 7 // Start is called before the first frame update 8 void Start() 9 { 10 11 } 12 13 private void OnTriggerEnter(Collider other) 14 { 15 //debug测试是否发生碰撞 16 Debug.Log(other.name + "碰到了我"); 17 //若是和本身碰撞的物体名称是player就中止 18 if(other.name == "Player") 19 Time.timeScale = 0; 20 21 } 22 }
此时功能已经基本完成,在建立游戏通关完成UI,游戏开始时隐藏UI,触发是显示UI,建立一个物体将该脚本挂在上面,此物体放在小球跑道上。此物体也是触发器。debug
1 using System.Collections; 2 using System.Collections.Generic; 3 using UnityEngine; 4 5 public class Finish : MonoBehaviour 6 { 7 // Start is called before the first frame update 8 void Start() 9 { 10 GameObject canvas = GameObject.Find("Canvas"); 11 canvas.transform.Find("Panel").gameObject.SetActive(false); 12 } 13 14 private void OnTriggerEnter(Collider other) 15 { 16 GameObject canvas = GameObject.Find("Canvas"); 17 canvas.transform.Find("Panel").gameObject.SetActive(true); 18 } 19 20 }