U++ 变换操作

📅 2026/7/16 22:01:56
U++ 变换操作
Relative坐标系Relative是相对于父组件增加的移动旋转方向和位移方向均受父类影响。如果A是B的父级B是C的父级即附加关系为B-SetupAttachment(A);C-SetupAttachment(B);C的Relative是相对于直接父组件B不是相对于最上层的A。例如A-SetWorldLocation(FVector(1000, 0, 0)); B-SetRelativeLocation(FVector(200, 0, 0)); C-SetRelativeLocation(FVector(50, 0, 0));运行后A的世界位置为1000B的世界位置为1200C的世界位置为1250。对Actor进行操作对Actor进行位移和旋转操作相当于对根组件进行操作。一、Actor位置操作1.获取当前位置FVector CurrentLocation GetActorLocation();2.直接设置位置SetActorLocation(FVector(500.0f, 0.0f, 100.0f));3.增加世界位移AddActorWorldOffset(FVector(100.0f, 0.0f, 0.0f));4.增加本地位移AddActorLocalOffset(FVector(100.0f, 0.0f, 0.0f));二、Actor旋转操作1.获取当前旋转FRotator CurrentRotation GetActorRotation();2.直接设置旋转SetActorRotation(FRotator(0.0f, 90.0f, 0.0f));注意FRotator的顺序是FRotator(Pitch, Yaw, Roll)名称围绕轴常见效果RollX 轴左右翻滚PitchY 轴抬头、低头YawZ 轴左转、右转3.增加世界旋转AddActorWorldRotation(FRotator(0.0f, 90.0f, 0.0f));4.增加本地旋转AddActorLocalRotation(FRotator(0.0f, 90.0f, 0.0f));三、同时设置位置和旋转FVector NewLocation(500.0f, 200.0f, 100.0f); FRotator NewRotation(0.0f, 90.0f, 0.0f); SetActorLocationAndRotation( NewLocation, NewRotation );四、整体Transform操作1.获取整体TransformFTransform CurrentTransform GetActorTransform();Transform中存储了位置、旋转、缩放信息可从中分别读取。FVector Location CurrentTransform.GetLocation(); FRotator Rotation CurrentTransform.GetRotation().Rotator(); FVector Scale CurrentTransform.GetScale3D();2.创建TransformFTransform(Rotation, Location, Scale)FTransform NewTransform( FRotator(0.0f, 90.0f, 0.0f), FVector(500.0f, 0.0f, 100.0f), FVector(2.0f, 2.0f, 2.0f) );3.设置整体TransformSetActorTransform(NewTransform);可以一次性修改位置、旋转和缩放。4.增加整体TransformAddActorLocalTransform(); AddActorWorldTransform();实际开发中位移和旋转通常分别控制这样更为清晰。五、缩放操作缩放也是一个FVector值。1.获取缩放FVector CurrentScale GetActorScale3D();2.设置缩放SetActorScale3D(FVector(2.0f, 2.0f, 2.0f));***3***.在原有基础上放大const FVector NewScale GetActorScale3D() * 1.1f; SetActorScale3D(NewScale);六、获取物体方向UE默认XForward 前方YRight 右方ZUp 上方FVector Forward GetActorForwardVector(); FVector Right GetActorRightVector(); FVector Up GetActorUpVector();对单个组件进行操作只有继承自USceneComponent的组件才有空间变换FVector WorldLocation MyStaticMesh-GetComponentLocation(); FRotator WorldRotation MyStaticMesh-GetComponentRotation(); FVector WorldScale MyStaticMesh-GetComponentScale(); FTransform WorldTransform MyStaticMesh-GetComponentTransform(); FVector Location WorldTransform.GetLocation(); FRotator Rotation WorldTransform.GetRotation().Rotator(); FVector Scale WorldTransform.GetScale3D();将一个向量变为单位向量FVector UnitVector OriginalVector.GetSafeNormal();该方法会检查向量长度是否过小。如果无法安全归一化默认返回零向量(0,0,0)因此实际开发中通常优先使用它。注意GetSafeNormal()返回新向量FVector Direction(3.0f, 4.0f, 0.0f); Direction.Normalize();Normalize()直接修改原向量返回Bool值。若只考虑xy平面可以使用FVector Direction2D (TargetLocation - CurrentLocation).GetSafeNormal2D();GetSafeNormal2D() 只归一化 X、Y 分量并把 Z 设置为 0。