【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

相关文章

hdu1043(八数码问题,广搜 + hash(实现状态压缩) )

利用康拓展开将一个排列映射成一个自然数,然后就变成了普通的广搜题。 #include<iostream>#include<algorithm>#include<string>#include<stack>#include<queue>#include<map>#include<stdio.h>#include<stdlib.h>#include<ctype.h>#inclu

【C++ Primer Plus习题】13.4

大家好,这里是国中之林! ❥前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站。有兴趣的可以点点进去看看← 问题: 解答: main.cpp #include <iostream>#include "port.h"int main() {Port p1;Port p2("Abc", "Bcc", 30);std::cout <<

C++包装器

包装器 在 C++ 中,“包装器”通常指的是一种设计模式或编程技巧,用于封装其他代码或对象,使其更易于使用、管理或扩展。包装器的概念在编程中非常普遍,可以用于函数、类、库等多个方面。下面是几个常见的 “包装器” 类型: 1. 函数包装器 函数包装器用于封装一个或多个函数,使其接口更统一或更便于调用。例如,std::function 是一个通用的函数包装器,它可以存储任意可调用对象(函数、函数

C++11第三弹:lambda表达式 | 新的类功能 | 模板的可变参数

🌈个人主页: 南桥几晴秋 🌈C++专栏: 南桥谈C++ 🌈C语言专栏: C语言学习系列 🌈Linux学习专栏: 南桥谈Linux 🌈数据结构学习专栏: 数据结构杂谈 🌈数据库学习专栏: 南桥谈MySQL 🌈Qt学习专栏: 南桥谈Qt 🌈菜鸡代码练习: 练习随想记录 🌈git学习: 南桥谈Git 🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈�

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

【Prometheus】PromQL向量匹配实现不同标签的向量数据进行运算

✨✨ 欢迎大家来到景天科技苑✨✨ 🎈🎈 养成好习惯,先赞后看哦~🎈🎈 🏆 作者简介:景天科技苑 🏆《头衔》:大厂架构师,华为云开发者社区专家博主,阿里云开发者社区专家博主,CSDN全栈领域优质创作者,掘金优秀博主,51CTO博客专家等。 🏆《博客》:Python全栈,前后端开发,小程序开发,人工智能,js逆向,App逆向,网络系统安全,数据分析,Django,fastapi

让树莓派智能语音助手实现定时提醒功能

最初的时候是想直接在rasa 的chatbot上实现,因为rasa本身是带有remindschedule模块的。不过经过一番折腾后,忽然发现,chatbot上实现的定时,语音助手不一定会有响应。因为,我目前语音助手的代码设置了长时间无应答会结束对话,这样一来,chatbot定时提醒的触发就不会被语音助手获悉。那怎么让语音助手也具有定时提醒功能呢? 我最后选择的方法是用threading.Time

Android实现任意版本设置默认的锁屏壁纸和桌面壁纸(两张壁纸可不一致)

客户有些需求需要设置默认壁纸和锁屏壁纸  在默认情况下 这两个壁纸是相同的  如果需要默认的锁屏壁纸和桌面壁纸不一样 需要额外修改 Android13实现 替换默认桌面壁纸: 将图片文件替换frameworks/base/core/res/res/drawable-nodpi/default_wallpaper.*  (注意不能是bmp格式) 替换默认锁屏壁纸: 将图片资源放入vendo

06 C++Lambda表达式

lambda表达式的定义 没有显式模版形参的lambda表达式 [捕获] 前属性 (形参列表) 说明符 异常 后属性 尾随类型 约束 {函数体} 有显式模版形参的lambda表达式 [捕获] <模版形参> 模版约束 前属性 (形参列表) 说明符 异常 后属性 尾随类型 约束 {函数体} 含义 捕获:包含零个或者多个捕获符的逗号分隔列表 模板形参:用于泛型lambda提供个模板形参的名

C#实战|大乐透选号器[6]:实现实时显示已选择的红蓝球数量

哈喽,你好啊,我是雷工。 关于大乐透选号器在前面已经记录了5篇笔记,这是第6篇; 接下来实现实时显示当前选中红球数量,蓝球数量; 以下为练习笔记。 01 效果演示 当选择和取消选择红球或蓝球时,在对应的位置显示实时已选择的红球、蓝球的数量; 02 标签名称 分别设置Label标签名称为:lblRedCount、lblBlueCount