How to properly enable physics in C++

Hi, I’m very new to unreal engine, so I have a simple question. I’m trying to enable physics on a object that has mesh loaded in the constructor, this is the code I use (based on tutorials):

// Sets default values
AShape::AShape()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don’t need it.
PrimaryActorTick.bCanEverTick = true;

UStaticMeshComponent* shape = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Shape"));
RootComponent=shape;
static ConstructorHelpers::FObjectFinder<UStaticMesh> shapeAsset(TEXT("/Game/Shape01"));
if (shapeAsset.Succeeded())
{
	UE_LOG(LogTemp, Warning, TEXT("Asset found"));
	shape->SetStaticMesh(shapeAsset.Object);
	shape->SetRelativeLocation(FVector(0.f, 0.f, 0.f));
	shape->SetSimulatePhysics(true);
	shape->WakeRigidBody();
}
else
{
	UE_LOG(LogTemp, Warning, TEXT("Asset NOT found"));
}

}

The mesh is properly loaded, but physics is not enabled. I can still enable the physics manually in the editor, and then it works, but I create objects like these procedural I cannot rely on that. Any idea what i’m doing wrong? Thank you!

Hello, BramV

In this situation, please check whether your StaticMeshComponent has been initialized correctly. Also note that in order for physics to work, collision component should be implemented properly too, which means it has an adequate shape and size. This is especially important if you are using a specific mesh object. In this case it is more convenient to add collision in the editor.

There are also different kinds of collision responses in Unreal Engine 4, which means there are different ways collision objects can interact with each other.

If you like to learn more, please check this reference on collision Collision Response Reference in Unreal Engine | Unreal Engine 5.1 Documentation

Hope this helped!
Cheers!

Hello there,

I know this is an old post but it never received a proper answer.
If you want to activate physics you need to enable the collision first and then to enable Simulate physics.

SetCollisionEnabled(ECollisionEnabled::PhysicsOnly);
SetSimulatePhysics(true);

As this post still appears from google search it deserved an answer.

3 Likes