UnrealScripterAI
Discord ↗
Link Copied to Clipboard
×
"Create an animated player movement system that simulates a real human"
// Header file UCLASS() class YOURGAME_API APlayerCharacter : public ACharacter { GENERATED_BODY() public: APlayerCharacter(); // Movement Input void MoveForward(float Value); void MoveRight(float Value); protected: // Animation Instances UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Animations") class UAnimMontage* WalkAnimation; UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Animations") class UAnimMontage* RunAnimation; // Called when the game starts or when spawned virtual void BeginPlay() override; // Called every frame virtual void Tick(float DeltaTime) override; // Called to bind functionality to input virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override; }; // Source file APlayerCharacter::APlayerCharacter() { // Set this character to call Tick() every frame. PrimaryActorTick.bCanEverTick = true; } void APlayerCharacter::BeginPlay() { Super::BeginPlay(); } void APlayerCharacter::Tick(float DeltaTime) { Super::Tick(DeltaTime); } void APlayerCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) { Super::SetupPlayerInputComponent(PlayerInputComponent); // Bind movement input PlayerInputComponent->BindAxis("MoveForward", this, &APlayerCharacter::MoveForward); PlayerInputComponent->BindAxis("MoveRight", this, &APlayerCharacter::MoveRight); } void APlayerCharacter::MoveForward(float Value) { if (Value != 0.0f) { // Determine animation to use based on movement speed UAnimMontage* AnimationToPlay = (GetVelocity().Size() > WalkRunThreshold) ? RunAnimation : WalkAnimation; // Play the animation if it's not already playing if (!GetMesh()->GetAnimInstance()->Montage_IsPlaying(AnimationToPlay)) { GetMesh()->GetAnimInstance()->Montage_Play(AnimationToPlay); } // Add movement input AddMovementInput(GetActorForwardVector(), Value); } else { // Stop the animation if it's playing GetMesh()->GetAnimInstance()->Montage_Stop(0.2f, WalkAnimation); GetMesh()->GetAnimInstance()->Montage_Stop(0.2f, RunAnimation); } } void APlayerCharacter::MoveRight(float Value) { if (Value != 0.0f) { // Determine animation to use based on movement speed UAnimMontage* AnimationToPlay = (GetVelocity().Size() > WalkRunThreshold) ? RunAnimation : WalkAnimation; // Play the animation if it's not already playing if (!GetMesh()->GetAnimInstance()->Montage_IsPlaying(AnimationToPlay)) { GetMesh()->GetAnimInstance()->Montage_Play(AnimationToPlay); } // Add movement input AddMovementInput(GetActorRightVector(), Value); } else { // Stop the animation if it's playing GetMesh()->GetAnimInstance()->Montage_Stop(0.2f, WalkAnimation); GetMesh()->GetAnimInstance()->Montage_Stop(0.2f, RunAnimation); } }