Question by
MainManMike7 · Sep 02, 2018 at 11:37 PM ·
knockback
My overall goal is to make a knockback system for my 2D game. I am able to add a force to an object based on the x and y values that I put in, but I want it to be based on which way the rigidbody is actually moving. Help Please :)
using System; using System.Collections; using System.Collections.Generic; using UnityEngine;
public class RedSword : MonoBehaviour {
public float knockback;
public Rigidbody2D rbOfEnemy;
public string nameOfEnemy;
public GameObject gO;
//Knockback direction
public Vector2 kbdir;
void Start () {
}
void Update ()
{
}
private void OnCollisionEnter2D(Collision2D collision)
{
nameOfEnemy = collision.collider.name;
gO = GameObject.Find(nameOfEnemy);
gO.GetComponent<Rigidbody2D>();
rbOfEnemy = gO.GetComponent<Rigidbody2D>();
if (collision.collider.tag == "Enemy" )
{
applyKnockback();
}
}
private void applyKnockback()
{ //I want to find out which direction the object is moving based on the rigidbody (kbdir)
rbOfEnemy.AddForce(kbdir * knockback * Time.deltaTime);
Invoke("removeKnockback", .001f);
}
private void removeKnockback()
{
//How do I stop force
}
}
Comment
Answer by DawdleDev · Sep 03, 2018 at 08:34 PM
in the OnCollisionEnter2D void,
kbdir = collision.transform.GetComponent<Rigidbody2D> ().velocity.normalized;
That should do the trick.
Your answer