I’m creating a C++ tile class for tiles (sprites) on a 2D game board. The tiles will need to respond to mouse clicks (e.g. to allow moving the pieces).
The events seem to be registered properly because updating the collision properties (e.g. un-/checking Simulation Generates Hit Events
, Generate Overlap Events
or Can Ever Affect Navigation
) from the editor while playing causes the clicks to work correctly. A freshly spawned tile (without in-editor edits) doesn’t respond to the same clicks, though.
Here’s my setup (from the constructor):
RootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("TileRoot"));
TileSpriteComponent = CreateDefaultSubobject<UPaperSpriteComponent>(TEXT("TileSprite"));
TileSpriteComponent->SetSprite(TileSprite);
TileSpriteComponent->RegisterComponentWithWorld(GetWorld());
TileSpriteComponent->AttachTo(RootComponent);
TileSpriteComponent->MarkRenderStateDirty(); // To make the updated sprite render
In BeginPlay(…), I have this:
OnClicked.AddUniqueDynamic(this, &ATerrainTile::OnClicked_Mouse);
Which simply logs a message (for now):
// The tile was clicked by the mouse
void ATerrainTile::OnClicked_Mouse()
{
UE_LOG(LogTemp, Warning, TEXT("Tile %dx%d clicked"), TileRow, TileColumn);
}
The tiles are using the BlockAllDynamic
collision preset and therefore are set to Block for Visibility traces.
A few different searches have found suggestions like these:
These lead me to try all these in various combinations in the constructor and in BeginPlay(…), all without success:
TileSpriteComponent->Mobility = EComponentMobility::Movable;
TileSpriteComponent->bGenerateOverlapEvents = true;
TileSpriteComponent->SetSimulatePhysics(true);
TileSpriteComponent->SetEnableGravity(false);
TileSpriteComponent->SetNotifyRigidBodyCollision(true);
TileSpriteComponent->SetCollisionEnabled(ECollisionEnabled::QueryAndPhysics);
SetActorEnableCollision(true);
I suspect I’m missing either a piece of the setup or some way to tell the engine to recheck the physics/collision, but I can’t seem to find it.
Can someone explain what I’m missing here?