ハンターの噛みつき
CoddyのUnityジャーニー「物理演算とゲームプレイ」セクションの一部。レッスン 63/71。
チャレンジ
中級ハンターに噛みつかせて、プレイヤーを後方に吹き飛ばしましょう。
Hunterに、[SerializeField] private float knockback = 12f;とvoid OnCollisionEnter(Collision collision)を追加します。- その中で、
collision.gameObject.TryGetComponent(out Health health)のとき、health.TakeDamage(1);を呼び出します。 - 次に、プレイヤーを押し飛ばします。ハンターからプレイヤーに向かう
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プレイグラウンド