(Unity)砲弾を発射するとノックバックする。

(スクリプト)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ShotShell_Reaction : MonoBehaviour
{
    public float speed;
    public GameObject shellPrefab;
    public AudioClip sound;

    // 追加
    private Rigidbody rb;
    public GameObject tank;

    // 追加
    private void Start()
    {
        rb = tank.GetComponent<Rigidbody>();
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            GameObject shell = Instantiate(shellPrefab, transform.position, Quaternion.identity);
            Rigidbody shellRb = shell.GetComponent();
            shellRb.AddForce(transform.forward * speed);
            AudioSource.PlayClipAtPoint(sound, transform.position);
            Destroy(shell, 5);

            // 追加
            rb.AddForce(-transform.forward * 3f,ForceMode.VelocityChange);
        }
    }
}