- Home /
Knockback not working properly
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 doesnt get knocked back in the right direction (the direction of what it colided 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;
}
}
Answer by myzzie · Aug 24, 2020 at 03:26 AM
You're setting a rigidbody's velocity to negative 15 in forward direction, resulting in a backwards direction in world space.
When the collision occurs. Store the knockback direction by taking target position and subtract origin position and normalize it.
Vector3 knockbackDirection = (gettingKnockedBacked.transform.positon - theKnockbacker).normalized;
//In coroutine
rb.velocity = knockbackDirection * knockbackForce;
Perfect! thanks for the help. such a dumb mistake i made too haha.