Set cursor location when the game starts

Hi guys,

So I’m working on a small RTS game and I have a minor issue. I implemented edge panning, i.e. the camera moves when the mouse cursor touches the edge of the screen. However, when I start the game, the mouse cursor is set to the top left corner of the screen. This means that the camera starts panning as soon as the game starts. I wanted to fix this by just setting the cursor’s starting position to the center of the screen. This proved more difficult than I imagined.

First, I just tried to change the cursor’s location in my player controller’s BeginPlay function:

void AMyPlayerController::BeginPlay()
{
	Super::BeginPlay();

	FVector2D ViewportSize;
	GetWorld()->GetGameViewport()->GetViewportSize(ViewportSize);
	SetMouseLocation(ViewportSize.X / 2, ViewportSize.Y / 2);
}

This did not work at all.

I tried moving this piece of the code to my player controller’s Tick function and just set the cursor’s location on the first tick. This also did not work.

To make sure the call to SetMouseLocation was doing anything at all, I called it on each frame. This set the cursor’s position to the center of the screen, but did not allow me to move the cursor in-game (obviously).

Even more confused, I decided to the set the cursor’s position only in the first two ticks. Something like this:

void AMyPlayerController::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);

	if (TickCounter < 2) // TickCounter initialized to 0 in the constructor.
	{
		FVector2D ViewportSize;
		GetWorld()->GetGameViewport()->GetViewportSize(ViewportSize);
		SetMouseLocation(ViewportSize.X / 2, ViewportSize.Y / 2);
		++TickCounter;
	}
}

This worked. The cursor was set to the center of the screen when the game started and I was able to move it afterwards.

I guess I could keep using this hack, but I’d rather know what the hell is going on here.

Is something executed after all the actors tick once which sets the cursor’s position back to (0, 0)? I tried to Google this, but nothing came up (maybe I don’t know what to search for).

1 Like

it could be that BeginPlay is getting called before the cursor stuff is even created because PlayerController is in charge of camera/viewport and all that. You would have to find some way of calling that function after the viewport is created, like when a widget is constructed.

Yeah, that’s how I’m interpreting it as well. Do you know any event/callback I could use to perform stuff after the cursor has definitely been initialized? I guess I’ll have to explore that avenue further.

Right now, I’m hunting down where all of the set mouse location functions are called within the code. There aren’t too many places, so maybe I’ll track down the culprit that way.