接住强化道具
Coddy Unity 游戏:打砖块 课程的第 15 课,共 19 课。
道具会自行检测接住它的情况:它的触发碰撞体碰到挡板的碰撞体,并且两个刚体都是运动学的,这就足以触发 OnTriggerEnter。它也会从球旁边掉过,所以会先检查标签。
枚举用于命名道具种类,每个预制件都在 Inspector 中设置自己的种类,因此一个脚本就能处理两种道具:
public enum Kind { Wide, Multiball }
public Kind kind;
if (kind == Kind.Multiball) Debug.Log("Three balls");other.GetComponent<Paddle>() 会查找道具碰到的对象上的 Paddle 脚本。目前,Widen 只会输出日志;下一课会让挡板变宽。
挑战
困难用挡板接住掉落的强化道具。
- 在
PowerUp中,添加public enum Kind { Wide, Multiball }和public Kind kind;(每个预制件都设置自己的类型)。 - 添加
OnTriggerEnter(Collider other):除非other.CompareTag("Paddle"),否则返回;如果是加宽道具,则调用other.GetComponent<Paddle>().Widen();,然后调用Destroy(gameObject); - 在
Paddle中,添加public void Widen(),暂时让它输出Wide paddle。
按下 Play,接住一个绿色道具:它会消失,控制台会显示 Wide paddle。然后点击 Check。
亲手试试
using UnityEngine;
using UnityEngine.InputSystem;
public class Paddle : MonoBehaviour
{
public float speed = 14f;
public float wallX = 8f; // 两侧墙壁的内侧面分别位于 -wallX 和 wallX 处
Rigidbody rb;
void Awake()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
float input = 0f;
if (Keyboard.current.leftArrowKey.isPressed || Keyboard.current.aKey.isPressed) input -= 1f;
if (Keyboard.current.rightArrowKey.isPressed || Keyboard.current.dKey.isPressed) input += 1f;
Vector3 target = rb.position + Vector3.right * input * speed * Time.fixedDeltaTime;
float halfWidth = transform.localScale.x / 2f;
target.x = Mathf.Clamp(target.x, -wallX + halfWidth, wallX - halfWidth);
rb.MovePosition(target);
}
}
Unity 游戏:打砖块中的所有课
自己练习: Unity 在线编辑器