【UE4 C++】实现旋转小球的第三人称自由视角

2023-10-12 10:59

本文主要是介绍【UE4 C++】实现旋转小球的第三人称自由视角,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

本文将介绍用C++实现一个简单的玩家可通过WASD控制移动,Shift进行加速,鼠标控制视角旋转和缩放的小球。

本人也只是一个UE4初学者,大佬勿喷。


一、技术难点

  • 小球通过角速度控制旋转,因此想实现自由视角相机,它就不能作为小球的子物体。
  • 小球的移动方向始终要保持与视野前方相同。

二、最终效果图

 

  • 模型资源链接:https://pan.baidu.com/s/1e2bavPacWwA6_pDHlcM0Tw 密码:na24
  • UE4项目以及源码:https://download.csdn.net/download/qq_31788759/10565311

三、核心代码模块

在此先将模块分类,使结构清晰明了,最后有完整代码,可具体查看。


1、首先创建组件

  • SphereBase.h(自己创建的C++类)下
    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "RootComp")class USceneComponent * RootComp;//声明根节点组件UPROPERTY(EditAnywhere, BlueprintReadWrite,Category = "SphereMeshComp")class UStaticMeshComponent * SphereMeshComp;//小球Mesh组件UPROPERTY(EditAnywhere, BlueprintReadWrite,Category = "CameraArmComp")class USpringArmComponent * CameraArmComp;//相机臂组件UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "CameraComp")class UCameraComponent * CameraComp;//相机组件
  •  SphereBase.cpp
    //创建组件RootComp = CreateDefaultSubobject<USceneComponent>(TEXT("RootComp"));SphereMeshComp = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("SphereBaseComp"));CameraArmComp = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraArmComp"));CameraComp = CreateDefaultSubobject<UCameraComponent>(TEXT("CameraComp"));//添加组件父子关系SphereMeshComp->SetupAttachment(RootComp);CameraArmComp->SetupAttachment(RootComp);CameraComp->SetupAttachment(CameraArmComp);//设置小球物理效果为真SphereMeshComp->SetSimulatePhysics(true);
  • 创建蓝图类继承该C++类后,组件已创建 

2、绑定按键输入

 

    //绑定前后左右移动PlayerInputComponent->BindAxis("MoveForward", this, &ASphereBase::MoveForward);PlayerInputComponent->BindAxis("MoveRight", this, &ASphereBase::MoveRight);//Shift按下与抬起PlayerInputComponent->BindAction("MoveQuick", IE_Pressed, this, &ASphereBase::MoveQuick);
PlayerInputComponent->BindAction("MoveQuick", IE_Released, this, &ASphereBase::MoveNormal);//相机上下左右旋转PlayerInputComponent->BindAxis("CameraYaw", this, &ASphereBase::YawCamera);PlayerInputComponent->BindAxis("CameraPitch", this, &ASphereBase::PitchCamera);//相机缩放PlayerInputComponent->BindAction("ZoomIn", IE_Pressed, this, &ASphereBase::ZoomIn);PlayerInputComponent->BindAction("ZoomIn", IE_Released, this, &ASphereBase::ZoomStop);PlayerInputComponent->BindAction("ZoomOut", IE_Pressed, this, &ASphereBase::ZoomOut);PlayerInputComponent->BindAction("ZoomIn", IE_Released, this, &ASphereBase::ZoomStop);

具体函数请查看完整代码 

3、相机自由视角

建议采用世界坐标系函数修改值,不要使用相对坐标系Relative函数,否则会遇到很多问题。


  • 小球移动控制
    if (!AngularVector.IsZero()){FVector NewVector = FVector(0, 0, 0);NewVector += AngularVector.X  * CameraArmComp->GetForwardVector() * SphereSpeed;NewVector += AngularVector.Y  * CameraArmComp->GetRight	Vector() * SphereSpeed;SphereMeshComp->SetPhysicsAngularVelocity(NewVector);//给小球施加角速度向量}
  • 相机臂左右旋转
    FRotator LRRotation = CameraArmComp->GetComponentRotation();LRRotation.Yaw += CameraInput.X;CameraArmComp->SetWorldRotation(LRRotation);
  • 相机臂上下旋转 
    FRotator UDRotation = CameraArmComp->GetComponentRotation();UDRotation.Pitch = FMath::Clamp(UDRotation.Pitch + CameraInput.Y, -80.0f, -15.0f);//控制上下视野范围CameraArmComp->SetWorldRotation(UDRotation);
  • 相机臂跟随小球
    FVector NewLocation = SphereMeshComp->GetComponentLocation();CameraArmComp->SetWorldLocation(NewLocation);

4、相机缩放 

    ZoomValue = FMath::Clamp<float>(ZoomValue, 0.0f, 1.0f);//基于ZoomFActor来混合控制相机的视域和弹簧臂的长度 0.0f对应90.0f 1500.0fCameraComp->FieldOfView = FMath::Lerp<float>(90.0f, 60.0f, ZoomValue);CameraArmComp->TargetArmLength = FMath::Lerp<float>(1500.0f, 500.0f, ZoomValue);

滚轮控制ZoomValue值的变化

四、完整代码

  •  Sphere.h
#pragma once#include "CoreMinimal.h"
#include "GameFramework/Pawn.h"
#include "SphereBase.generated.h"//必须放在头文件最后UCLASS()
class BILICODE_API ASphereBase : public APawn//APawn 继承 Actor
{GENERATED_BODY()public:// Sets default values for this pawn's propertiesASphereBase();UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "RootComp")class USceneComponent * RootComp;UPROPERTY(EditAnywhere, BlueprintReadWrite,Category = "SphereMeshComp")class UStaticMeshComponent * SphereMeshComp;//class声明UPROPERTY(EditAnywhere, BlueprintReadWrite,Category = "CameraArmComp")class USpringArmComponent * CameraArmComp;UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "CameraComp")class UCameraComponent * CameraComp;public:FVector AngularVector;float SphereSpeed;float SpeedMin;float SpeedMax;FVector CameraInput;float ZoomValue;UPROPERTY(EditAnyWhere, BlueprintReadWrite)bool IsInput;//控制是否能输入按键protected:// Called when the game starts or when spawnedvirtual void BeginPlay() override;public:	// Called every framevirtual void Tick(float DeltaTime) override;// Called to bind functionality to inputvirtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;UFUNCTION(BlueprintCallable)void MoveForward(float AxisValue);UFUNCTION(BlueprintCallable)void MoveRight(float AxisValue);UFUNCTION(BlueprintCallable)void MoveQuick();UFUNCTION(BlueprintCallable)void MoveNormal();void PitchCamera(float AxisValue);void YawCamera(float AxisValue);void StartJump();void StopJump();void ZoomIn();void ZoomStop();void ZoomOut();
};
  • Sphere.cpp
// Fill out your copyright notice in the Description page of Project Settings.#include "SphereBase.h"
#include "Components/StaticMeshComponent.h"//Mesh头文件
#include "GameFramework/SpringArmComponent.h"//摄像机手臂头文件
#include "Camera/CameraComponent.h"
#include "Components/SceneComponent.h"
#include "Components/InputComponent.h"//输入按键绑定头文件
#include "Engine.h"// Sets default values
ASphereBase::ASphereBase()
{// 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;IsInput = true;SphereSpeed = 300.0f;SpeedMin = SphereSpeed;SpeedMax = 500.0f;ZoomValue = 0.5f;//创建组件RootComp = CreateDefaultSubobject<USceneComponent>(TEXT("RootComp"));SphereMeshComp = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("SphereBaseComp"));CameraArmComp = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraArmComp"));CameraComp = CreateDefaultSubobject<UCameraComponent>(TEXT("CameraComp"));//组件关系SphereMeshComp->SetupAttachment(RootComp);CameraArmComp->SetupAttachment(RootComp);CameraComp->SetupAttachment(CameraArmComp);//设置物理效果为真SphereMeshComp->SetSimulatePhysics(true);
}// Called when the game starts or when spawned
void ASphereBase::BeginPlay()
{Super::BeginPlay();
}// Called every frame
void ASphereBase::Tick(float DeltaTime)
{Super::Tick(DeltaTime);if (!AngularVector.IsZero()){FVector NewVector = FVector(0, 0, 0);NewVector += AngularVector.X  * CameraArmComp->GetForwardVector() * SphereSpeed;NewVector += AngularVector.Y  * CameraArmComp->GetRightVector() * SphereSpeed;SphereMeshComp->SetPhysicsAngularVelocity(NewVector);//小球向一个向量方向旋转移动}{//相机臂左右旋转(相机臂与小球是兄弟关系FRotator LRRotation = CameraArmComp->GetComponentRotation();LRRotation.Yaw += CameraInput.X;CameraArmComp->SetWorldRotation(LRRotation);}{//相机臂跟随小球FVector NewLocation = SphereMeshComp->GetComponentLocation();CameraArmComp->SetWorldLocation(NewLocation);//两种方便的调试方法//GEngine->AddOnScreenDebugMessage(-1, 3.f, FColor::Purple, NewLocation.ToString());/*DrawDebugLine(GetWorld(),SphereBeginLocation,SphereMeshComp->GetComponentLocation(),FColor::Red,false, -1, 0,3.);*/}{//相机臂上下旋转FRotator UDRotation = CameraArmComp->GetComponentRotation();UDRotation.Pitch = FMath::Clamp(UDRotation.Pitch + CameraInput.Y, -80.0f, -15.0f);//控制旋转范围CameraArmComp->SetWorldRotation(UDRotation);}{//相机缩放ZoomValue = FMath::Clamp<float>(ZoomValue, 0.0f, 1.0f);//基于ZoomFActor来混合相机的视域和弹簧臂的长度CameraComp->FieldOfView = FMath::Lerp<float>(90.0f, 60.0f, ZoomValue);CameraArmComp->TargetArmLength = FMath::Lerp<float>(1500.0f, 500.0f, ZoomValue);}
}// Called to bind functionality to input
void ASphereBase::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)//pawn不同于actor的地方,用于绑定按键
{Super::SetupPlayerInputComponent(PlayerInputComponent);PlayerInputComponent->BindAxis("MoveForward", this, &ASphereBase::MoveForward);//绑定 前后移动映射 的函数PlayerInputComponent->BindAxis("MoveRight", this, &ASphereBase::MoveRight);//绑定左右PlayerInputComponent->BindAction("MoveQuick", IE_Pressed, this, &ASphereBase::MoveQuick);PlayerInputComponent->BindAction("MoveQuick", IE_Released, this, &ASphereBase::MoveNormal);PlayerInputComponent->BindAxis("CameraYaw", this, &ASphereBase::YawCamera);PlayerInputComponent->BindAxis("CameraPitch", this, &ASphereBase::PitchCamera);PlayerInputComponent->BindAction("ZoomIn", IE_Pressed, this, &ASphereBase::ZoomIn);PlayerInputComponent->BindAction("ZoomIn", IE_Released, this, &ASphereBase::ZoomStop);PlayerInputComponent->BindAction("ZoomOut", IE_Pressed, this, &ASphereBase::ZoomOut);PlayerInputComponent->BindAction("ZoomIn", IE_Released, this, &ASphereBase::ZoomStop);
}//前后左右输入控制
void ASphereBase::MoveForward(float AxisValue)
{if (IsInput){AngularVector.Y = FMath::Clamp<float>(AxisValue, -1.0f, 1.0f);}
}void ASphereBase::MoveRight(float AxisValue)
{if (IsInput){AngularVector.X = FMath::Clamp<float>(AxisValue, -1.0f, 1.0f);}
}
//shift输入控制
void ASphereBase::MoveQuick()
{SphereSpeed = SpeedMax;
}void ASphereBase::MoveNormal()
{SphereSpeed = SpeedMin;
}
//相机旋转输入控制
void ASphereBase::PitchCamera(float AxisValue)
{CameraInput.Y = AxisValue;
}void ASphereBase::YawCamera(float AxisValue)
{CameraInput.X = AxisValue;
}void ASphereBase::ZoomIn()
{ZoomValue += 0.1f;
}
//相机缩放输入控制
void ASphereBase::ZoomStop()
{
}void ASphereBase::ZoomOut()
{ZoomValue -= 0.1f;
}

 

这篇关于【UE4 C++】实现旋转小球的第三人称自由视角的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/195379

相关文章

Linux下删除乱码文件和目录的实现方式

《Linux下删除乱码文件和目录的实现方式》:本文主要介绍Linux下删除乱码文件和目录的实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录linux下删除乱码文件和目录方法1方法2总结Linux下删除乱码文件和目录方法1使用ls -i命令找到文件或目录

SpringBoot+EasyExcel实现自定义复杂样式导入导出

《SpringBoot+EasyExcel实现自定义复杂样式导入导出》这篇文章主要为大家详细介绍了SpringBoot如何结果EasyExcel实现自定义复杂样式导入导出功能,文中的示例代码讲解详细,... 目录安装处理自定义导出复杂场景1、列不固定,动态列2、动态下拉3、自定义锁定行/列,添加密码4、合并

mybatis执行insert返回id实现详解

《mybatis执行insert返回id实现详解》MyBatis插入操作默认返回受影响行数,需通过useGeneratedKeys+keyProperty或selectKey获取主键ID,确保主键为自... 目录 两种方式获取自增 ID:1. ​​useGeneratedKeys+keyProperty(推

Spring Boot集成Druid实现数据源管理与监控的详细步骤

《SpringBoot集成Druid实现数据源管理与监控的详细步骤》本文介绍如何在SpringBoot项目中集成Druid数据库连接池,包括环境搭建、Maven依赖配置、SpringBoot配置文件... 目录1. 引言1.1 环境准备1.2 Druid介绍2. 配置Druid连接池3. 查看Druid监控

Linux在线解压jar包的实现方式

《Linux在线解压jar包的实现方式》:本文主要介绍Linux在线解压jar包的实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录linux在线解压jar包解压 jar包的步骤总结Linux在线解压jar包在 Centos 中解压 jar 包可以使用 u

c++ 类成员变量默认初始值的实现

《c++类成员变量默认初始值的实现》本文主要介绍了c++类成员变量默认初始值,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录C++类成员变量初始化c++类的变量的初始化在C++中,如果使用类成员变量时未给定其初始值,那么它将被

C++中NULL与nullptr的区别小结

《C++中NULL与nullptr的区别小结》本文介绍了C++编程中NULL与nullptr的区别,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编... 目录C++98空值——NULLC++11空值——nullptr区别对比示例 C++98空值——NUL

C++ Log4cpp跨平台日志库的使用小结

《C++Log4cpp跨平台日志库的使用小结》Log4cpp是c++类库,本文详细介绍了C++日志库log4cpp的使用方法,及设置日志输出格式和优先级,具有一定的参考价值,感兴趣的可以了解一下... 目录一、介绍1. log4cpp的日志方式2.设置日志输出的格式3. 设置日志的输出优先级二、Window

Qt使用QSqlDatabase连接MySQL实现增删改查功能

《Qt使用QSqlDatabase连接MySQL实现增删改查功能》这篇文章主要为大家详细介绍了Qt如何使用QSqlDatabase连接MySQL实现增删改查功能,文中的示例代码讲解详细,感兴趣的小伙伴... 目录一、创建数据表二、连接mysql数据库三、封装成一个完整的轻量级 ORM 风格类3.1 表结构

基于Python实现一个图片拆分工具

《基于Python实现一个图片拆分工具》这篇文章主要为大家详细介绍了如何基于Python实现一个图片拆分工具,可以根据需要的行数和列数进行拆分,感兴趣的小伙伴可以跟随小编一起学习一下... 简单介绍先自己选择输入的图片,默认是输出到项目文件夹中,可以自己选择其他的文件夹,选择需要拆分的行数和列数,可以通过