标签:c++ unreal engine character constraint
在最新的Unreal Engine 4.4版本中,Blueprint内的PhysicsConstraint是有bug的,Blueprint不能编辑Constraint的两个Actor组件,唯一的方法是通过C++代码来实现。还有很多这样的问题,好在源代码都给你了,想怎么改随自己。
我想在ThirdPerson这个模板里实现角色荡秋千的功能,就像波斯猴子里面这种。
首先,给Character Blueprint添加一个UPhysicsConstraintComponent:
UPROPERTY(VisibleDefaultsOnly, Category = "NanConstraint")
TSubobjectPtr<class UPhysicsConstraintComponent> ConstraintComp;
还需要一个固定的物理对象,当栓绳子的桩子,所以再添加一个USphereComponent:
UPROPERTY(VisibleDefaultsOnly, Category = "NanConstraint")
TSubobjectPtr<class USphereComponent> BlockSphere;
在Character的构造函数中初始化它们:
//创建Constraint Component
ConstraintComp = PCIP.CreateDefaultSubobject<UPhysicsConstraintComponent>(this, TEXT("ConstraintComp"));
FConstraintInstance ConstraintInst;
ConstraintComp->ConstraintInstance = ConstraintInst;
BlockSphere = PCIP.CreateDefaultSubobject<USphereComponent>(this, TEXT("BlockComponent"));
定义两个方法Swing()和UnSwing(),一个启动Constraint,一个断开Constraint
void ANanProjectCharacter::Swing()
{
FVector CharLocation = GetActorLocation();
FVector SphereLocation = CharLocation + FVector(0, 0, ConstraintLen);
CapsuleRot = CapsuleComponent->GetComponentRotation();
BlockSphere->SetWorldLocation(SphereLocation);
CapsuleComponent->SetSimulatePhysics(true);
ConstraintComp->SetWorldLocation(SphereLocation);
ConstraintComp->SetConstrainedComponents(BlockSphere, NAME_None, CapsuleComponent, NAME_None);
}
void ANanProjectCharacter::UnSwing()
{
CapsuleComponent->SetSimulatePhysics(false);
ConstraintComp->BreakConstraint();
CapsuleComponent->SetWorldRotation(CapsuleRot);
}
需要注意的是,Character的CapsuleComponent本身是不启用物理模拟的,为了让他摆起来,需要在启用Constraint之后,将他加入物理模拟。当然断开的时候,也别忘了再次禁用它。CapsuleRot保存启用物理模拟前,CapsuleComponent的旋转,如果不修正,角色断开Constraint之后很可能是头朝下的,很喜感。
Unreal Engine 4 C++代码动态创建Constraint
标签:c++ unreal engine character constraint
原文地址:http://blog.csdn.net/shangguanwaner/article/details/39429663