UE4 CPP例子代码

例1  控制一个物体的移动,放大缩小
//
Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Pawn.h" #include "MyPawn.generated.h" UCLASS() class FIRSTCPP_API AMyPawn : public APawn { GENERATED_BODY() public: // Sets default values for this pawn's properties AMyPawn(); protected: // Called when the game starts or when spawned virtual void BeginPlay() override; public: // Called every frame virtual void Tick(float DeltaTime) override; // Called to bind functionality to input virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override; void Move_XAxis(float AxisValue); void Move_YAxis(float AxisValue); void StartGrowing(); void StopGrowing(); UPROPERTY(EditAnyWhere) UStaticMeshComponent* OurVisibleComponent; FVector CurrentVelocity; bool bGrowing; }; // Fill out your copyright notice in the Description page of Project Settings. #include "MyPawn.h" #include "Camera/CameraComponent.h" // Sets default values AMyPawn::AMyPawn() { // Set this pawn to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; AutoPossessPlayer = EAutoReceiveInput::Player0; RootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("RootComponent11")); UCameraComponent* OurCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("OurCamera11")); OurVisibleComponent = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("OurVisibleComponent11")); OurCamera->AttachTo(RootComponent); OurCamera->SetRelativeLocation(FVector(-250.0, 0.0f, 250.0f)); OurCamera->SetRelativeRotation(FRotator(-45.0,0.0f,0.0f)); OurVisibleComponent->AttachTo(RootComponent); } // Called when the game starts or when spawned void AMyPawn::BeginPlay() { Super::BeginPlay(); } // Called every frame void AMyPawn::Tick(float DeltaTime) { Super::Tick(DeltaTime); float CurrentScale = OurVisibleComponent->GetComponentScale().X; if (bGrowing) { CurrentScale += DeltaTime; } else { CurrentScale -= (DeltaTime * 0.5f); } CurrentScale = FMath::Clamp(CurrentScale, 1.0f, 2.0f); OurVisibleComponent->SetWorldScale3D(FVector(CurrentScale)); if (!CurrentVelocity.IsZero()) { FVector NewLocation = GetActorLocation() + (CurrentVelocity * DeltaTime); SetActorLocation(NewLocation); } } // Called to bind functionality to input void AMyPawn::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) { Super::SetupPlayerInputComponent(PlayerInputComponent); PlayerInputComponent->BindAction("Grow", IE_Pressed, this, &AMyPawn::StartGrowing); PlayerInputComponent->BindAction("Grow",IE_Released,this,&AMyPawn::StopGrowing); PlayerInputComponent->BindAxis("MoveX",this,&AMyPawn::Move_XAxis); PlayerInputComponent->BindAxis("MoveY",this,&AMyPawn::Move_YAxis); } void AMyPawn::Move_XAxis(float AxisValue) { CurrentVelocity.X = FMath::Clamp(AxisValue, -1.0f, 1.0f) *100.0f; } void AMyPawn::Move_YAxis(float AxisValue) { CurrentVelocity.Y = FMath::Clamp(AxisValue,-1.0f,1.0f) *100.0f; } void AMyPawn::StartGrowing() { bGrowing = true; } void AMyPawn::StopGrowing() { bGrowing = false; }

例2   CameraDirector

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

#pragma once

#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "CameraDirector.generated.h"

UCLASS()
class FIRSTCPP_API ACameraDirector : public AActor
{
    GENERATED_BODY()
    
public:    
    // Sets default values for this actor's properties
    ACameraDirector();

protected:
    // Called when the game starts or when spawned
    virtual void BeginPlay() override;

public:    
    // Called every frame
    virtual void Tick(float DeltaTime) override;

    UPROPERTY(EditAnyWhere)
    AActor*  CameraOne;

    UPROPERTY(EditAnyWhere)
    AActor*  CameraTwo;

    float  TimeToNextCameraChange;
};


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

#include "CameraDirector.h"
#include"Kismet/GameplayStatics.h"

// Sets default values
ACameraDirector::ACameraDirector()
{
     // Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
    PrimaryActorTick.bCanEverTick = true;

}

// Called when the game starts or when spawned
void ACameraDirector::BeginPlay()
{
    Super::BeginPlay();
    
}

// Called every frame
void ACameraDirector::Tick(float DeltaTime)
{
    Super::Tick(DeltaTime);

    const float TimeBetweenCameraChanges = 2.0f;
    const float SmoothBlendTime = 0.75f;
    TimeToNextCameraChange -= DeltaTime;
    if (TimeToNextCameraChange <= 0.0f)
    {
        TimeToNextCameraChange += TimeBetweenCameraChanges;

        APlayerController*  OurPlayerController = UGameplayStatics::GetPlayerController(this, 0);
        if (OurPlayerController)
        {
            if ((OurPlayerController->GetViewTarget() != CameraOne) && (CameraOne != NULL))
            {
                OurPlayerController->SetViewTarget(CameraOne);
            }
            else if(OurPlayerController->GetViewTarget() != CameraTwo)
            {
                OurPlayerController->SetViewTargetWithBlend(CameraTwo,SmoothBlendTime);

            }
        }
    }


}

例3  计时器

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

#pragma once

#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "Components/TextRenderComponent.h"
#include "countdown.generated.h"

UCLASS()
class FIRSTCPP_API Acountdown : public AActor
{
    GENERATED_BODY()
    
public:    
    // Sets default values for this actor's properties
    Acountdown();

protected:
    // Called when the game starts or when spawned
    virtual void BeginPlay() override;

public:    
    // Called every frame
    virtual void Tick(float DeltaTime) override;

    void UpdateTimerDisplay();
    void AdvanceTimer();
    void CountdownHasFinished();

    FTimerHandle  CountdownTimerHandle;

    int32 CountdownTime;

    UTextRenderComponent*  CountdownText;

};



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

#include "countdown.h"

// Sets default values
Acountdown::Acountdown()
{
     // Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
    PrimaryActorTick.bCanEverTick = true;

    CountdownText = CreateDefaultSubobject<UTextRenderComponent>(TEXT("countdowntext"));
    CountdownText->SetHorizontalAlignment(EHTA_Center);
    CountdownText->SetWorldSize(150.0);

    RootComponent = CountdownText;

    CountdownTime = 3;


}

// Called when the game starts or when spawned
void Acountdown::BeginPlay()
{
    Super::BeginPlay();
    
    UpdateTimerDisplay();

    GetWorldTimerManager().SetTimer(CountdownTimerHandle,this,&Acountdown::AdvanceTimer,1.0f,true);

}

// Called every frame
void Acountdown::Tick(float DeltaTime)
{
    Super::Tick(DeltaTime);

}


void Acountdown::UpdateTimerDisplay()
{
    CountdownText->SetText(FString::FromInt(FMath::Max(CountdownTime, 0)));
}


void Acountdown::AdvanceTimer()
{
    --CountdownTime;

    UpdateTimerDisplay();
    if (CountdownTime < 1)
    {
        GetWorldTimerManager().ClearTimer(CountdownTimerHandle);
        CountdownHasFinished();

    }
}
void Acountdown::CountdownHasFinished()
{
    CountdownText->SetText(TEXT("Go"));
}

例4  控制相机旋转和移动

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

#pragma once

#include "CoreMinimal.h"
#include "GameFramework/Pawn.h"
#include "GameFramework/Character.h"
#include"GameFramework/SpringArmComponent.h"
#include"Camera/CameraComponent.h"


#include "pawnWithCamera.generated.h"


UCLASS()
class TESTPROJECT_API ApawnWithCamera : public APawn
{
    GENERATED_BODY()

public:
    // Sets default values for this pawn's properties
    ApawnWithCamera();

protected:
    // Called when the game starts or when spawned
    virtual void BeginPlay() override;

public:    
    // Called every frame
    virtual void Tick(float DeltaTime) override;

    // Called to bind functionality to input
    virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;

    void MoveForward(float AxisValue);
    void MoveRight(float AxisValue);
    void PitchCamera(float AxisValue);
    void YawCamera(float AxisValue);
    void ZoomIn();
    void ZoomOut();


    UPROPERTY(EditAnyWhere)
    USpringArmComponent* m_SpringArm;

    UCameraComponent* m_Camera;

    FVector2D  m_MovementInput;
    FVector2D  m_CameraInput;
    float      m_ZoomFactor;
    bool       m_bZoomingIn;


};



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


#include "pawnWithCamera.h"

// Sets default values
ApawnWithCamera::ApawnWithCamera()
{
     // Set this pawn to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
    PrimaryActorTick.bCanEverTick = true;

    RootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("rootComponent"));

    m_SpringArm = CreateDefaultSubobject<USpringArmComponent>(TEXT("springarm"));

    m_SpringArm->AttachTo(RootComponent);
    m_SpringArm->SetRelativeLocationAndRotation(FVector(0.0,0.0f,50.0),FRotator(-60.0,0.0,0.0));

    m_SpringArm->TargetArmLength = 400.0f;
    m_SpringArm->bEnableCameraLag = true;
    m_SpringArm->CameraLagSpeed = 3.0f;


    m_Camera = CreateDefaultSubobject<UCameraComponent>(TEXT("camera"));
    m_Camera->AttachTo(RootComponent);

    AutoPossessPlayer = EAutoReceiveInput::Player0;


}

// Called when the game starts or when spawned
void ApawnWithCamera::BeginPlay()
{
    Super::BeginPlay();
    
}

// Called every frame
void ApawnWithCamera::Tick(float DeltaTime)
{
    Super::Tick(DeltaTime);
    

    if (m_bZoomingIn)
    {
        m_ZoomFactor += DeltaTime * 2.0f;
    }
    else
    {
        m_ZoomFactor -= DeltaTime * 2.0f;
    }

    m_ZoomFactor = FMath::Clamp<float>(m_ZoomFactor,0.0f,1.0f);
    m_Camera->FieldOfView = FMath::Lerp<float>(90.0, 60.0f, m_ZoomFactor);

    m_SpringArm->TargetArmLength = FMath::Lerp<float>(400.0, 300.0, m_ZoomFactor);

    {

        FRotator  NewRotator = GetActorRotation();
        NewRotator.Yaw += m_CameraInput.X;

        SetActorRotation(NewRotator);



    }

    {

        
        //FRotator newRotation = m_SpringArm->GetComponentRotation();
        FRotator newRotation = GetActorRotation();
        newRotation.Pitch = FMath::Clamp<float>(newRotation.Pitch + m_CameraInput.Y, -80.0, 85.0);
        //m_SpringArm->SetWorldRotation(newRotation);
        SetActorRotation(newRotation);
        
        FString showdebug = FString::SanitizeFloat(newRotation.Pitch) + FString("::")+ FString::SanitizeFloat(m_CameraInput.Y);
        //GEngine->AddOnScreenDebugMessage(-1, 1.0f, FColor::Blue, showdebug);
    }
    if(!m_MovementInput.IsZero())
    {
        m_MovementInput = m_MovementInput.GetSafeNormal() * 100.0f;
        FVector newLocation = GetActorLocation();

        newLocation += GetActorForwardVector() * m_MovementInput.X * DeltaTime;
        newLocation += GetActorRightVector() * m_MovementInput.Y * DeltaTime;

        SetActorLocation(newLocation);


    }
}

// Called to bind functionality to input
void ApawnWithCamera::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
    Super::SetupPlayerInputComponent(PlayerInputComponent);


    PlayerInputComponent->BindAction("ZoomIn",IE_Pressed,this,&ApawnWithCamera::ZoomIn);
    PlayerInputComponent->BindAction("ZoomIn",IE_Released,this,&ApawnWithCamera::ZoomOut);

    PlayerInputComponent->BindAxis("MoveForward",this,&ApawnWithCamera::MoveForward);
    PlayerInputComponent->BindAxis("MoveRight",this,&ApawnWithCamera::MoveRight);
    PlayerInputComponent->BindAxis("CameraPitch",this,&ApawnWithCamera::PitchCamera);
    PlayerInputComponent->BindAxis("CameraYaw",this,&ApawnWithCamera::YawCamera);

    GEngine->AddOnScreenDebugMessage(-1, 4.0f, FColor::Red, FString("Setup Player Component"));

}

void ApawnWithCamera::MoveForward(float AxisValue)
{
    m_MovementInput.X = FMath::Clamp<float>(AxisValue, -1, 1);

    //GEngine->AddOnScreenDebugMessage(-1, 1.0f, FColor::Red, FString("Player Moveforward"));
}
void ApawnWithCamera::MoveRight(float AxisValue)
{
    m_MovementInput.Y = FMath::Clamp<float>(AxisValue, -1, 1);

    //GEngine->AddOnScreenDebugMessage(-1, 1.0f, FColor::Red, FString("Player MoveRight"));
}
void ApawnWithCamera::PitchCamera(float AxisValue)
{
    m_CameraInput.Y = AxisValue;


    FString::SanitizeFloat(AxisValue);
    GEngine->AddOnScreenDebugMessage(-1, 1.0f, FColor::Red, FString("Player Pitch") + FString::SanitizeFloat(AxisValue));

    //GEngine->AddOnScreenDebugMessage(-1, 1.0f, FColor::Red, FString("Player Pitch"));
}
void ApawnWithCamera::YawCamera(float AxisValue)
{
    m_CameraInput.X = AxisValue;

    FString::SanitizeFloat(AxisValue);
    //GEngine->AddOnScreenDebugMessage(-1, 1.0f, FColor::Red, FString("Player Yaw")+ FString::SanitizeFloat(AxisValue));
}
void ApawnWithCamera::ZoomIn()
{
    m_bZoomingIn = true;
}
void ApawnWithCamera::ZoomOut()
{
    m_bZoomingIn = false;
}
原文地址:https://www.cnblogs.com/dragon2012/p/14499101.html