文章目录
警告:
动画蓝图不需要运行游戏也会一直执行,因此在编写代码时非常容易引发空指针崩溃
因此编写动画蓝图时需要关闭UE,或严格执行空指针检查
创建动画蓝图
继承AnimInstance
常用属性如下
头文件
csharp
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Animation/AnimInstance.h"
#include "SlashAnimInstance.generated.h"
class ASlashCharacter;
/**
*
*/
UCLASS()
class CPPLEARN_API USlashAnimInstance : public UAnimInstance
{
GENERATED_BODY()
public:
virtual void NativeInitializeAnimation() override;
virtual void NativeUpdateAnimation(float DeltaSeconds) override;
UPROPERTY(BlueprintReadOnly)
ASlashCharacter* SlashCharacter; //使用这个动画蓝图的角色
UPROPERTY(BlueprintReadOnly,Category=Movement)
class UCharacterMovementComponent* SlashCharacterMovement; //角色的运动组件
UPROPERTY(BlueprintReadOnly,Category=Movement)
float GroundSpeed;//地面速度
};
源文件
cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "Character/SlashAnimInstance.h"
#include "Character/SlashCharacter.h"
#include "GameFramework/CharacterMovementComponent.h"
#include "Kismet/KismetMathLibrary.h"
void USlashAnimInstance::NativeInitializeAnimation()
{
Super::NativeInitializeAnimation();
SlashCharacter = Cast<ASlashCharacter>(TryGetPawnOwner());//获取角色 TryGetPawnOwner获取到的是pawn,需要强转成character
if (SlashCharacter)
{
SlashCharacterMovement = SlashCharacter->GetCharacterMovement();//获取角色的运动组件
}
}
void USlashAnimInstance::NativeUpdateAnimation(float DeltaSeconds)
{
Super::NativeUpdateAnimation(DeltaSeconds);
if (SlashCharacter)
{
GroundSpeed = UKismetMathLibrary::VSizeXY( SlashCharacterMovement->Velocity);//获取地面速度,只考虑xy方向,使用kismet数学库提供的方法
}
}