UE4 C++学习笔记之给Pawn增加自制移动组件(实现碰撞滑行)

任务:给Pawn添加自制移动组件,使其碰到障碍物时沿着碰撞的边缘滑行

第一步:新建运动组件C++类MyMovementComponent

MyMovementComponent.h代码如下:

#pragma once

#include "CoreMinimal.h"
#include "GameFramework/PawnMovementComponent.h"
#include "MyPawnMovementComponent.generated.h"

/**
 * 
 */
UCLASS()
class LEARNTEST_API UMyPawnMovementComponent : public UPawnMovementComponent
{
	GENERATED_BODY()

public:
        //继承自PawnMovementComponent类,需重写TickComponent方法
	virtual void TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override;

};

MyMovementComponent.cpp代码如下:


#include "MyPawnMovementComponent.h"

void UMyPawnMovementComponent::TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
    Super::TickComponent(DeltaTime, TickType, ThisTickFunction);

    // 确保所有事物持续有效,以便进行移动。
    if (!PawnOwner || !UpdatedComponent || ShouldSkipUpdate(DeltaTime))
    {
        return;
    }

    // 获取(然后清除)ACreature::Tick中设置的移动向量
    FVector DesiredMovementThisFrame = ConsumeInputVector().GetClampedToMaxSize(1.0f) * DeltaTime * 300.0f;
    if (!DesiredMovementThisFrame.IsNearlyZero())
    {
        FHitResult Hit;
        SafeMoveUpdatedComponent(DesiredMovementThisFrame, UpdatedComponent->GetComponentRotation(), true, Hit);

        // 若发生碰撞,尝试滑过去
        if (Hit.IsValidBlockingHit())
        {
            SlideAlongSurface(DesiredMovementThisFrame, 1.f - Hit.Time, Hit.Normal, Hit);
        }
    }
};

第二步:在Pawn类Creature中添加MyMovementComponent移动组件

Creature.h关键代码如下:

public:
    
        //声明移动组件指针
	UPROPERTY()    
	class UMyPawnMovementComponent* OurMovementComponent;

private:
        //声明前后移动函数
	void MoveForward(float Value);
        //声明左右移动函数
	void MoveRight(float Value);

Creature.c关键代码如下:

1、在构造函数中创建运动组件并将其运动和根组件绑定

	OurMovementComponent = CreateDefaultSubobject<UMyPawnMovementComponent>(TEXT("CustomMovementComponent"));
	OurMovementComponent->UpdatedComponent = RootComponent;

2、实现前后左右移动函数

void ACreature::MoveForward(float Value)
{
	if (OurMovementComponent && (OurMovementComponent->UpdatedComponent == RootComponent))
	{
		OurMovementComponent->AddInputVector(GetActorForwardVector() * Value);
	}
}

void ACreature::MoveRight(float Value)
{
	if (OurMovementComponent && (OurMovementComponent->UpdatedComponent == RootComponent))
	{
		OurMovementComponent->AddInputVector(GetActorRightVector() * Value);
	}
}

第三步:Pawn拥有称为GetMovementComponent的函数,用于提供引擎中其他类访问该Pawn当前所使用的Pawn移动组件的权限。需覆盖该函数,从而返回自定义Pawn移动组件。

1、在Creature.h中添加该重写声明

public:
    	virtual UPawnMovementComponent* GetMovementComponent() const override;

2、在Creature.cpp中实现该函数

UPawnMovementComponent* ACreature::GetMovementComponent() const
{
	return OurMovementComponent;
}

其他细节可参考以下虚幻官方文档:https://docs.unrealengine.com/zh-CN/Programming/Tutorials/Components/index.html

猜你喜欢

转载自blog.csdn.net/weixin_44928892/article/details/108059061