触发器

实例:实现一个移动的小球

球体运动脚本

通过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
{
// Start is called before the first frame update
public float speed=10;
public float turnspeed=10;

// Update is called once per frame
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))//按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;//游戏结束
}
}
}


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!