Entity knockback

Hi, can someone please tell me how to add knock-back? My entities have x,y,velocityX and velocityY variables, and i have just no idea how to add it. I can like add 5 to velocityX for example, but how do i decrease it? And if the entity has bumped into something and it’s velocity is set to 0, how do i make it so that it stops decreasing?Maybe add separate fields, but that destroys the purpose of one velocity vector, doesn’t it? Please help me :c

PS: Using Artemis.

It’s probably a bad way of doing it, but this is my code for knockback to give you an idea


	public void knockback(float r, float force){
		r = r - 180;
		
		force *= knockbackResistance; // how heavy the entity is (so lesser knock back)
		
		knockbackTimer = force * 8;
		knockbackTo = new Vector2((force * (float) MathUtils.sin(r * MathUtils.degreesToRadians)),
						       (-force * (float) MathUtils.cos(r * MathUtils.degreesToRadians)))
			                              .add(position);
					
	}

Then I have this on the update loop for the entity


	public void update(){
		if(knockbackTimer > 0){
			position = Tools.lerp(position, knockbackTo, 0.2f);
			knockbackTimer -= Gdx.graphics.getDeltaTime() * 1000;
		}
        }

Whoa i didn’t expect code! Thanks ;D ! I think i will add knockbackTimer an knockbackTo to the Velocity component and do the logic in some system. Thanks again ;D !

PS : r is radians , right? Or degrees?

I would recommend against having knockback specifically in the entity. Instead you should have an acceleration attribute. You could just use a vector for acceleration. You then apply acceleration to speed every update. Then you apply friction to acceleration right after. This way anything that affects the entity can just change acceleration.

Please note that applying friction to acceleration makes no sense. Apply it to velocity. Acceleration (caused by a force) is immediately zero after it is processed, as the knockback force is instantaneous.

Instead of having an acceleration vector as field(s), I’d do this:


class Entity
{
   Vec2 position;
   Vec2 velocity;
   float mass;
   Vec2 force;
   float drag;

   public void tick() {
      Vec2 acceleration = new Vec2(force).div(mass);
      force.set(0,0,0);
      velocity.add(acceleration);
      position.add(velocity);
      velocity.mul(1.0f - drag);
   }
}

Whether this fits in your game logic, is another matter :slight_smile:

According to Riven’s logic, also ensure tick() is being called at a consistent rate (like 30fps or something).

Ah, yes. I have this assumption that everybody is sensible enough to have a fixed logic rate, and a dynamic render rate.

(Please don’t let this derail in a fixed/delta step discussion!)