UE小计:AlignActorToMouse

C++版

// Fill out your copyright notice in the Description page of Project Settings.


#include "HitWhereverYouWant.h"

#include "KismetTraceUtils.h"
#include "Kismet/GameplayStatics.h"

void UHitWhereverYouWant::AlignActorToMouse(AActor* ActorToAlign)
{
	const auto World = GWorld->GetGameInstance()->GetWorld();
	const APlayerController* PlayerController = UGameplayStatics::GetPlayerController(World, 0);
	if (PlayerController && ActorToAlign && World)
	{
		// 获取鼠标的屏幕坐标
		float MouseX, MouseY;
		if (PlayerController->GetMousePosition(MouseX, MouseY))
		{
			// 将屏幕坐标转换为世界空间中的一条射线(起点和方向)
			FVector WorldLocation, WorldDirection;
			if (PlayerController->DeprojectScreenPositionToWorld(MouseX, MouseY, WorldLocation, WorldDirection))
			{
				// 执行射线投射
				FHitResult HitResult;
				FVector StartPoint = WorldLocation;
				FVector EndPoint = StartPoint + WorldDirection * 10000.0f; // 射线长度可以根据需要调整
				FCollisionQueryParams CollisionParams;
				CollisionParams.AddIgnoredActor(ActorToAlign); // 忽略射线投射目标Actor本身

				bool bHit = World->LineTraceSingleByChannel(
					HitResult,
					StartPoint,
					EndPoint,
					ECC_Visibility, // 或者你需要的其他碰撞通道
					CollisionParams
				);

				if (bHit)
				{
					// 获取ActorToAlign的位置
					FVector ActorLocation = ActorToAlign->GetActorLocation();

					// 计算从ActorToAlign指向命中点的方向
					FVector ToHitDirection = (HitResult.ImpactPoint - ActorLocation).GetSafeNormal();

					// 计算新的旋转,使得ActorToAlign的Z轴指向命中点
					FRotator NewRotation = FRotationMatrix::MakeFromZ(ToHitDirection).Rotator();

					// 应用新的旋转到ActorToAlign
					ActorToAlign->SetActorRotation(NewRotation);
				}
			}
		}
	}
}

UE小计:AlignActorToMouse_第1张图片

蓝图版

UE小计:AlignActorToMouse_第2张图片

你可能感兴趣的:(UE)