[UE4]获取鼠标点击时的坐标

本文介绍了在UE4中如何获取鼠标和触屏点击时的坐标。通过PlayerController可以获取鼠标在场景坐标系中的位置,范围为1000米x1000米。通过注册鼠标事件并实现MoveToMouseCursor函数,在PlayerTick中调用。此外,使用PlayerController::GetMousePosition()可获取显示屏内的鼠标坐标。对于触屏设备,同样可以通过注册触屏事件并利用Viewport接口来获取场景内的点击位置。

使用PlayerController获取

1,获取鼠标在当前场景中坐标系统的中的position,加入场景地图的范围是一千平方米,那么这个position的范围也是1000米x1000米。

注册鼠标事件

FInputActionBinding &action1 = InputComponent->BindAction("SetDestination", IE_Pressed, this, &AHPlayerController::OnSetDestinationPressed);

 函数实现MoveToMouseCursor(),此函数放在PlayerController::PlayerTick()内调用,重写下PlayerTick():

void AHPlayerController::MoveToMouseCursor()
{
	// Trace to see what is under the mouse cursor
	FHitResult Hit;
	GetHitResultUnderCursor(ECC_Visibility, false, Hit);

	if (Hit.bBlockingHit)
	{
		// We hit something, move there
		SetNewMoveDestination(Hit.ImpactPoint);
	}
}

 

2,获取鼠标再显示屏内的坐标系统的position。假如屏幕分辨率是1280x720,那么这个position的范围就是(0, 0)到(1280, 720)。PlayerController::GetMousePosition()。

AHPlayerController* PC = ...

float LocX = 0;
float LocY = 0;
PC->GetMousePosition(LocX, LocY);

 

3,触屏设备上获取场景内点击的position,其范围与第1种情况相同。

注册touch事件

InputComponent->BindTouch(EInputEvent::IE_Pressed, this, &AHPlayerController::MoveToTouchLocation);

 函数实现:

void AHPlayerController::MoveToTouchLocation(const ETouchIndex::Type FingerIndex, const FVector Location)
{
	FVector2D ScreenSpaceLocation(Location);

	// Trace to see what is under the touch location
	FHitResult HitResult;
	GetHitResultAtScreenPosition(ScreenSpaceLocation, CurrentClickTraceChannel, true, HitResult);
	if (HitResult.bBlockingHit)
	{
		// We hit something, move there
		SetNewMoveDestination(HitResult.ImpactPoint);
	}
}

 

使用Viewport接口获取

//坐标值是整数
FIntPoint MousePoint;
GEngine->GameViewport->Viewport->GetMousePos(MousePoint);

//坐标是标准float
FVector2D CursorPos;
GEngine->GameViewport->GetMousePosition(CursorPos);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值