How to set widget position to cursor position? C++

I’ve been struggling with this for days now.
I need a custom cursor on-screen at all times. I already have the cursor coordinates, but I don’t know how to get the UMG Widget objects and change its properties.

I have a UMG Widget blueprint with an Image object. I want to set the image position and texture within a C++ class.

Also which is the best class to use for main menus and cursors? Should I use a HUD class? I’m currently experimenting inside the PlayerController class.

MyPlayerController.h

#pragma once

#include "CoreMinimal.h"
#include "GameFramework/PlayerController.h"
#include "MyPlayerController.generated.h"

/**
 * Used for HUD controls, Main Menu, Inventory.
 */
UCLASS()
class CPP_PROTOTYPE_API AMyPlayerController : public APlayerController
{
	GENERATED_BODY()

public:
    virtual void Tick(float DeltaTime) override;
public:
		float MouseXPos;
		float MouseYPos;
};

MyPlayerController.cpp

#include "MyPlayerController.h"
#include "Kismet/GameplayStatics.h" // temp


void AMyPlayerController::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);
	GetMousePosition(MouseXPos, MouseYPos);
	UE_LOG(LogTemp, Warning, TEXT("Mouse Location: %f, %f"), 
    MouseXPos, MouseYPos);
}

UCanvasPanelSlot has the function SetDesiredPosition(FVector2D).

The widget that you want to call this function from needs to be a slot (which is like a child but for the UMG layout hierarchy) of UCanvasPanel.

Then you get the slot from that widget, and cast that to UCanvasPanelSlot, from there you can call SetDesiredPosition() and pass in the FVector2D from the PlayerController’s function to get mouse FVector2D.

For example, let’s say you want to adjust the location of a UUniformGridPanel to the mouse position.

UUniformGridPanel has to be a slot of a UCanvasPanel.

UUniformGridPanel* MyGridPanel;
UCanvasPanelSlot* GridAsPanelSlot = Cast<UCanvasPanelSlot>(MyGridPanel->Slot);
GridAsPanelSlot->SetDesiredPosition(MousePositionVector);

Something along those lines.

1 Like