致命区域
本课属于 Coddy Unity 学习旅程的“物理与游戏玩法”单元。第 19 课,共 71 课。
死亡区域是设置在玩家不能到达的地方的触发器,例如熔岩、尖刺或关卡下方的虚空。玩家进入其中后会被送回生成点。这里由熔岩自身的脚本完成此操作,生成点则在 Inspector 中设置的 Transform 字段里:
public Transform spawnPoint;
void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
other.transform.position = spawnPoint.position;
other.attachedRigidbody.linearVelocity = Vector3.zero;
}
}other.attachedRigidbody 是进入触发器的碰撞体所属的 Rigidbody。设置 transform.position 会让玩家瞬间传送,这正是重生所需要的效果。不过,Rigidbody 会在跳跃过程中保留速度:以每秒 10 个单位的速度掉进熔岩的玩家,到达生成点时仍会以每秒 10 个单位的速度下坠;而冲进熔岩的玩家则会继续向前冲,径直再次掉进去。将 linearVelocity 设置为 Vector3.zero 后,玩家到达时就会静止站立。标签检查会让其他掉进熔岩的物体留在原处。
挑战
简单让玩家能够重生。这个脚本挂在玩家身上,所以要移动 transform 和 body,而不是 other。
- 在
Start()中,将Vector3 respawn字段设为transform.position。 - 在
OnTriggerEnter(Collider other)中,当other.CompareTag("Checkpoint")时,设置respawn = transform.position;。 - 当
other.CompareTag("KillZone")时,设置transform.position = respawn;和body.linearVelocity = Vector3.zero;。
按下“开始”,然后走下桥。接着点击“检查”。
亲手试试
using UnityEngine;
public class Player : MonoBehaviour
{
public float force = 12f;
Rigidbody body;
Vector3 input;
// 重生点:玩家返回的位置
void Start()
{
body = GetComponent<Rigidbody>();
}
void Update()
{
input = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical"));
}
void FixedUpdate()
{
body.AddForce(input * force);
}
// Checkpoint:记住玩家的位置。KillZone:让玩家回到那里并保持静止。
}
物理与游戏玩法中的所有课
自己练习: Unity 在线编辑器