I am making a 3D game and have added a feature that if the Bot collides with a specific object, it gets knocked back.
I am using a NavMeshAgent
for the bot and this goes against the Rigidbody
so I disable one and enable the other for the knockback. the problem is that the bot doesn’t get knocked back in the right direction (the direction of what it collided from) and it is also inconsistent with how far it gets knocked back.
This is the script for it:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class KnockBack : MonoBehaviour
{
private NavMeshAgent nma = null;
private Rigidbody rb;
public bool applyKnockBack;
void Start()
{
nma = GetComponentInParent<NavMeshAgent>();
rb = GetComponent<Rigidbody>();
}
void Update()
{
if(applyKnockBack)
{
StartCoroutine(KnockBackCo());
applyKnockBack = false;
}
}
void OnCollisionEnter(Collision col)
{
if (col.gameObject.tag == "Finish" || col.gameObject.tag == "Player")
{
StartCoroutine(KnockBackCo());
}
}
IEnumerator KnockBackCo()
{
nma.enabled = false;
rb.isKinematic = false;
rb.velocity = Vector3.forward * -15;
yield return new WaitForSeconds(0.5f);
nma.enabled = true;
rb.isKinematic = true;
}
}
Perfect! thanks for the help. such a dumb mistake i made too haha.
– Abacus