#knockback direction issue.

4 messages · Page 1 of 1 (latest)

uncut ivy
#

I have an issue with knockback effect. When I hit an enemy with a shield, enemy always knocked back into left direction, which provides instability, any suggestion on fixing it?

Video: https://www.veed.io/view/9289929e-3dfb-42cb-827c-add890213d01?sharingWidget=true&panel=share

using UnityEngine;
using System.Collections;

public class KnockbackEffect : MonoBehaviour
{
    public float knockbackForce = 500f;
    public float knockbackDuration = 0.5f;
    public Rigidbody2D rb;
    public GameObject effectSparkles;

    private Coroutine knockbackCoroutine;
    private Transform _transform;

    private void Awake()
    {
        _transform = transform;
        rb = GetComponent<Rigidbody2D>();
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag("Shield"))
        {
            if (knockbackCoroutine != null)
            {
                StopCoroutine("ApplyKnockback");
            }

            if (rb != null)
            {
                Vector2 knockbackDirection = (_transform.position - other.transform.position).normalized;
                knockbackCoroutine = StartCoroutine(ApplyKnockback(knockbackDirection));
                Debug.Log("KnockBack");
            }

            if (effectSparkles != null)
            {
                Instantiate(effectSparkles, _transform.position, Quaternion.identity);
            }
        }
    }

    private IEnumerator ApplyKnockback(Vector2 direction)
    {
        rb.velocity = Vector2.zero;
        rb.AddForce(direction * knockbackForce, ForceMode2D.Impulse);

        yield return new WaitForSeconds(knockbackDuration);

        rb.velocity = Vector2.zero;
        knockbackCoroutine = null;
    }
}
fast current
unkempt willow
#

Bro, Vector2 is x and y. Did you make your game in X AND Z?

#

BTW.

  • Instantiate is bad design, use pooling.
  • You do not need to declare knockbackDirection every single time.