实例:实现一个移动的小球
球体运动脚本
通过transform的translate函数来改变实体的位置,是实现移动的一种基础方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| using System.Collections; using System.Collections.Generic; using UnityEditor; using UnityEngine; using UnityEngine.SceneManagement;
public class move : MonoBehaviour { public float speed=10; public float turnspeed=10; void Update() { float x = Input.GetAxis("Horizontal"); transform.Translate(x * turnspeed * Time.deltaTime, 0, speed * Time.deltaTime); if (transform.position.x < -4 || transform.position.x > 4) { transform.Translate(x * turnspeed * Time.deltaTime, -10 * Time.deltaTime, speed * Time.deltaTime); } if (transform.position.y < -15) { Time.timeScale = 0; } if (Input.GetKeyDown(KeyCode.R)) { SceneManager.LoadScene(0); Time.timeScale = 1; return; } Transform c = Camera.main.transform; Quaternion cur = c.rotation; Quaternion target = cur * Quaternion.Euler(0, 0, x *0.5f); Camera.main.transform.rotation = Quaternion.Slerp(cur, target, 0.25f); } }
|
触发器脚本
小球碰到障碍物后要结束游戏,通过设置触发器完成
注意障碍物要勾选is trigger选项
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| using System.Collections; using System.Collections.Generic; using UnityEngine;
public class reach : MonoBehaviour { private void OnTriggerEnter(Collider other) { if (other.name == "Sphere") { Time.timeScale = 0; } } }
|