Download

Player knockback.

Hello guys,

I’ve been stuck with this problem for a while now, and I simply have no idea at all how to do it.
I want to create a knockback, when the player gets hit by a bullet, in my case the standard Projectile Actor. I also want to, that if the player got knocked back once, the next time the knockback is a little more, and so on.

Does anyone have any clue on how to do this? (The code would help but some explanation is appreciated.)

Thanks in advance, Robin. (UE4 Beginner)

I made a subclass of CharacterMovement that makes a character stumble.

There’s a function CalcVelocity you can override.

I copy pasted some code from my game that could help point you in the right direction.



void UWR2CharacterMovement::CalcVelocity(float DeltaTime, float Friction, bool bFluid, float BrakingDeceleration)
{
	Super::CalcVelocity(DeltaTime, Friction, bFluid, BrakingDeceleration);

	//TODO: (Engine)
	//logic copied from super method to abort early, with every engine update be sure this is copied
	if (!HasValidData() || HasAnimRootMotion() || DeltaTime < MIN_TICK_TIME || (CharacterOwner && CharacterOwner->Role == ROLE_SimulatedProxy))
	{
		return;
	}

	//apply stumble velocity when on ground
	if (IsMovingOnGround())
	{
		Velocity = (Velocity + GetStumbleVelocity()).GetClampedToMaxSize(GetMaxStumblingSpeed());
	}
}

//This code makes a character bounce against walls when stumbling
void UWR2CharacterMovement::HandleImpact(FHitResult const& Hit, float TimeSlice, const FVector& MoveDelta)
{
	Super::HandleImpact(Hit, TimeSlice, MoveDelta);

	//bounce the character's stumble while making the stumble velocity lower a little bit
	if (Hit.bBlockingHit && IsMovingOnGround() && StumbleMagnitudes.GetCurrentTotalMagnitude() > StumbleBounceThreshold)
	{
		//convert to 2D vectors
		FVector2D HitNormal = FVector2D(Hit.Normal);
		FVector2D MoveDir = FVector2D(Hit.TraceEnd - Hit.TraceStart);
		MoveDir.Normalize();

		//compute the bounce dir
		StumbleDirection = MoveDir - FVector2D::DotProduct(HitNormal, MoveDir) * HitNormal * 2.f;
		StumbleDirection.Normalize();	//just to be sure

		//lower the bounce magnitude
		StumbleMagnitudes.Multiply(StumbleBounceDampening);
	}
}