I have a player moved by transform.translate. I need the player to knock back when it is hit by an enemy and I’m using Addforce for this but it isn’t working. Here’s the script. Thank you!
public float PlaneSpeed;
public float maxXLeft;
public float maxYUp;
public float maxXRight;
public float maxYDown;
Rigidbody2D rb;
public bool knockBack;
public float thrust;
public static MovePlane instance;
void Awake()
{
if (instance == null)
{
instance = this;
}
}
void Start() {
rb = GetComponent<Rigidbody2D>();
}
void Update () {
if (knockBack)
{
rb.AddForce(transform.right * thrust);
knockBack = !knockBack;
}
else
{
float axisX = Input.GetAxis("Horizontal");
float axisY = Input.GetAxis("Vertical");
transform.Translate(new Vector3(axisX, axisY) * Time.deltaTime * PlaneSpeed);
}
Vector3 pos = transform.position;
pos.x = Mathf.Clamp(pos.x, maxXLeft, maxXRight);
pos.y = Mathf.Clamp(pos.y, maxYDown, maxYUp);
transform.position = pos;
}
void OnTriggerEnter2D(Collider2D col2)
{
if (col2.gameObject.tag == "Enemy")
{
knockBack = true;
}