Menu
CoddyTech

猎人的撕咬

本课属于 Coddy Unity 学习旅程的“物理与游戏玩法”单元。第 63 课,共 71 课。

challenge icon

挑战

中等

让猎人咬到玩家,并把玩家击退。

  1. 在 Hunter 中,添加 [SerializeField] private float knockback = 12f; 和 void OnCollisionEnter(Collision collision)。
  2. 在方法内部,当 collision.gameObject.TryGetComponent(out Health health) 成立时,调用 health.TakeDamage(1);。
  3. 然后将它推开:away 的方向从猎人指向玩家,将 y 设为 0,并调用 collision.rigidbody.AddForce(away.normalized * knockback, ForceMode.Impulse);。

按下“运行”,看看你能坚持多久。然后点击“检查”。

亲手试试

using UnityEngine;

public class Hunter : MonoBehaviour
{
    [SerializeField] private float speed = 3f;
    private Rigidbody rb;
    private Transform player;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
        player = GameObject.FindWithTag("Player").transform;
    }

    void FixedUpdate()
    {
        Vector3 toPlayer = player.position - rb.position;
        toPlayer.y = 0f;
        Vector3 dir = toPlayer.normalized;
        rb.linearVelocity = new Vector3(dir.x * speed, rb.linearVelocity.y, dir.z * speed);
    }
}

物理与游戏玩法中的所有课

自己练习: Unity 在线编辑器