Using knockback code with transform.Translate C#

Hi everybody!

So me and my friends are trying to make a 2D topdown RPG. We have most of our player movement and interaction code done, but we want the player (and the enemies) to be knocked back when struck. Our first thought was to use add.force but since we are using transform.Translate for the player movement, we are not actually adding any force to the player. This results in the player endlessly floating away.

Is there a smart way to solve this problem and still keep our transform.Translate code? If so, we would very much appropriate any help and/or tips. :slight_smile:

Oh, here’s our movement code if it would be of any use.

private void TranslateMe()
	{
		
		float t = speed * Time.deltaTime;
		
		if (Input.GetKey ("s")) 
		{
			transform.Translate (-Vector2.up * t);
			return;
		}
		if (Input.GetKey ("w")) 
		{
			transform.Translate (Vector2.up * t);
			return;
		}
		if (Input.GetKey ("a")) 
		{
			transform.Translate (-Vector2.right * t);
			return;
		}
		if (Input.GetKey ("d")) 
		{
			transform.Translate (Vector2.right * t);
			return;
		}

Honestly I’d toss the translate and replace it with force movement if you want to use physics at all in your game. You’ll also want force movement if you want to handle collisions in an efficient way. Doing this would allow you to use addforce to knockback the enemies.

Depends on how you want the knockback to work. I agree with unitylover, it’s probably better to do it that way, but if you just want to finish your game and you don’t really care about it being well made (like we all do for small projects that are for fun/learning), I guess you can make the knockback a forced move command? Like, being hit from above is equal to the player pressing s?