当前位置: 代码迷 >> 综合 >> UE4 使用C++重写UPawnMovementComponent,做出沿着对象滑动的效果
  详细解决方案

UE4 使用C++重写UPawnMovementComponent,做出沿着对象滑动的效果

热度:61   发布时间:2023-10-24 02:20:34.0

一、要做出滑动的效果,主要是针对对象的摩檫力下功夫

1.头文件代码如下:

// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

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

/**
 * 
 */
UCLASS()
class MYFIRSTPROJECT_API UColliderMovementComponent : public UPawnMovementComponent
{
    GENERATED_BODY()
    
public:
    virtual void TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override;
};

2.Cpp代码如下:

// Fill out your copyright notice in the Description page of Project Settings.


#include "ColliderMovementComponent.h"

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

    if (!PawnOwner || !UpdatedComponent || ShouldSkipUpdate(DeltaTime)) 
    {
        return;
    }

    //从Collider获取并清除Vector
    FVector DesiredMovementThisFrame = ConsumeInputVector().GetClampedToMaxSize(1.0f) * DeltaTime * 150.f;

    if (!DesiredMovementThisFrame.IsNearlyZero()) 
    {
        FHitResult Hit;
        SafeMoveUpdatedComponent(DesiredMovementThisFrame, UpdatedComponent->GetComponentRotation(), true, Hit);

        //如果撞到了其他对象,沿着对象滑动过去
        if (Hit.IsValidBlockingHit()) 
        {
            SlideAlongSurface(DesiredMovementThisFrame, 1.f - Hit.Time, Hit.Normal, Hit);
        }
    }
}

  相关解决方案