UE4射击游戏中添加瞄准到敌人时准星变红的效果

主要思路是,建立一个接口Unreal Interface,对需要检测的敌人添加这个接口,当射线检测Result对象继承了该接口时,就让HUD中的准星颜色变红。

首先新建一个Unreal Interface:

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

#pragma once

#include "CoreMinimal.h"
#include "UObject/Interface.h"
#include "InteractWithCrosshairsInterface.generated.h"

// This class does not need to be modified.
UINTERFACE(MinimalAPI)
class UInteractWithCrosshairsInterface : public UInterface
{
    
    
	GENERATED_BODY()
};

/**
 * 
 */
class TPS_API IInteractWithCrosshairsInterface
{
    
    
	GENERATED_BODY()

	// Add interface functions to this class. This is the class that will be inherited to implement this interface.
public:
};

对武器射线检测的返回值进行检测,对这个Result进行GetActor(),判断这个Actor是否实现了接口,若实现,就将准星颜色置为红,否则置为白。射线检测是每帧执行的:

if(TraceHitResult.GetActor() && TraceHitResult.GetActor()->Implements<UInteractWithCrosshairsInterface>())
{
    
    
	HUDPackage.CrosshairColor = FLinearColor::Red;
}
else
{
    
    
	HUDPackage.CrosshairColor = FLinearColor::White;
}

这个HUDPackage是一个FHUDPackage类型结构体,用来显示准星,主要包含上下左右中几个Texture变量、准星扩散速度以及准星颜色。在我的项目中,其定义如下:

USTRUCT(BlueprintType)
struct FHUDPackage
{
    
    
	GENERATED_BODY()
	
public:
	UTexture2D* CrosshairsCenter;
	UTexture2D* CrosshairsLeft;
	UTexture2D* CrosshairsRight;
	UTexture2D* CrosshairsTop;
	UTexture2D* CrosshairsBottom;
	float CrosshairSpread;
	FLinearColor CrosshairColor;
};

在射线检测到实现了接口的对象时,将HUD中的CrosshairColor改变颜色即可。最后不要忘记在敌人类中继承这个接口:

class TPS_API AEnemy : public ACharacter, public IInteractWithCrosshairsInterface

猜你喜欢

转载自blog.csdn.net/weixin_47260762/article/details/127543687