in my 2d top down game, i want my player to experience knockback when they get in contact with an enemy but i cant seem to simulate it no matter what i do! heres the problem. i get hit the right amount then the next time i get hit i get hit twice the amount and it keeps on knocking me back more so i just deleted it
can anyone show me how to add knockback? (im kinda stupid :P)
heres movement code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
[Header("Movement and Rotation")]
public int moveSpeed;
Vector2 movement;
Vector2 mousePos;
[Header("Knockback")]
public float kb;
public float kbStunTime;
bool canMove;
[Header("References")]
public Camera cam;
public Rigidbody2D playerRb;
private void Start()
{
canMove = true;
}
// Update is called once per frame
void Update()
{
movement.x = Input.GetAxisRaw("Horizontal");
movement.y = Input.GetAxisRaw("Vertical");
mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
}
private void FixedUpdate()
{
if (canMove)
{
playerRb.MovePosition(playerRb.position + (movement * moveSpeed * Time.fixedDeltaTime));
}
Vector2 lookDir = mousePos - playerRb.position;
float angle = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg;
playerRb.rotation = angle;
}
private void OnCollisionEnter2D(Collision2D collision)
{
if(collision.gameObject.CompareTag("Enemy"))
{
//Vector2 dir = transform.position - collision.gameObject.transform.position;
canMove = false;
//playerRb.AddForce(dir * kb, ForceMode2D.Impulse);
StartCoroutine(KnockbackStunTime(kbStunTime));
}
}
IEnumerator KnockbackStunTime(float cooldown)
{
yield return new WaitForSeconds(cooldown);
canMove = true;
}
}