Unreal C++:如何通过代码单独修改特定Static Mesh的旋转
仅用C++实现Unreal Engine 5中单独旋转螺旋桨静态网格体
要实现仅旋转螺旋桨而非整个潜艇,核心是直接操作螺旋桨对应的UStaticMeshComponent,而非旋转整个Actor。以下是具体步骤:
1. 在C++类中声明可暴露给蓝图的组件引用
在你的Actor类头文件(比如SubmarineActor.h)中,添加一个可编辑的UStaticMeshComponent属性,用于关联蓝图里的螺旋桨组件:
#pragma once #include "CoreMinimal.h" #include "GameFramework/Actor.h" #include "SubmarineActor.generated.h" UCLASS() class YOURPROJECT_API ASubmarineActor : public AActor { GENERATED_BODY() public: ASubmarineActor(); protected: virtual void BeginPlay() override; public: virtual void Tick(float DeltaTime) override; // 声明螺旋桨静态网格组件,允许在蓝图中赋值 UPROPERTY(EditAnywhere, Category = "Propeller Setup") UStaticMeshComponent* PropellerMesh; // 旋转参数,可在编辑器调整 UPROPERTY(EditAnywhere, Category = "Propeller Setup") float RotationSpeed = 180.0f; // 每秒旋转180度 };
2. 在Tick函数中单独旋转螺旋桨组件
在对应的cpp文件(SubmarineActor.cpp)中,修改Tick逻辑,直接操作PropellerMesh的旋转,而非整个Actor:
#include "SubmarineActor.h" ASubmarineActor::ASubmarineActor() { PrimaryActorTick.bCanEverTick = true; } void ASubmarineActor::BeginPlay() { Super::BeginPlay(); } void ASubmarineActor::Tick(float DeltaTime) { Super::Tick(DeltaTime); if (PropellerMesh) { // 计算本次Tick需要旋转的角度 float RotationAmount = RotationSpeed * DeltaTime; // 绕Z轴旋转(可根据你的螺旋桨朝向调整轴) PropellerMesh->AddLocalRotation(FRotator(0, 0, RotationAmount)); } }
3. 在蓝图中关联螺旋桨组件
编译C++代码后,打开你的潜艇蓝图类:
- 在蓝图的Details面板中找到你声明的
Propeller Setup分类 - 将编辑器中已添加的螺旋桨静态网格组件拖入
PropellerMesh属性框中
这样运行游戏时,只有螺旋桨会按照设定的速度旋转,整个潜艇不会被带动。
为什么你的原有代码会旋转整个潜艇
你之前的代码通过GetOwner()获取了整个Actor,调用SetActorRotation()会修改Actor根节点的旋转,自然会带动所有子组件(包括潜艇主体)。UE的Actor是组件化结构,要单独控制某个部件,必须直接操作对应的组件。
内容的提问来源于stack exchange,提问作者Caio
相关产品推荐
相关产品推荐

