射击游戏案例(四)

2024-05-24 16:36
文章标签 游戏 案例 射击

本文主要是介绍射击游戏案例(四),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、瞄准偏移(AimOffset)

现在已经给角色添加了射击和准星,当角色在Pitch轴上偏移的时候,一般的游戏中都会有角色的手臂武器进行朝向的改变,比如角色向上看,手臂武器的指向向上。

附虚幻引擎5.2版本瞄准偏移如何创建、使用:5.2版本瞄准偏移

在将瞄准偏移所用到的动画帧批处理的时候,在附加设置处要注意附加动画类型、基础姿势类型、基础姿势动画设置好。

 创建出来之后,将做好的单帧动画拖入。

 CharacterAnim.h

UPROPERTY(EditAnywhere,BlueprintReadOnly,Category=Properties,meta=(AllowPrivateAccess="true"))
float PitchValue = 0.0f;//俯仰值

CharacterAnim.cpp

void UCharacterAnim::NativeUpdateAnimation(float DeltaSeconds)
{Super::NativeUpdateAnimation(DeltaSeconds);if (!CharacterRef){CharacterRef = Cast<AManCharacter>(TryGetPawnOwner());}else{FVector CharacterVelocity = CharacterRef->GetVelocity();Speed = CharacterVelocity.Size();IsInAir = CharacterRef->GetMovementComponent()->IsFalling();Direction = CalculateDirection(CharacterVelocity,CharacterRef->GetControlRotation());const FRotator CharacterRotator = CharacterRef->GetActorRotation();const FRotator ControlRotator = CharacterRef->GetControlRotation();const FRotator DeltaRotator = UKismetMathLibrary::NormalizedDeltaRotator(ControlRotator,CharacterRotator);const FRotator CurrentRotator = FRotator(PitchValue,0.0f,0.0f);const FRotator TargetRotator = UKismetMathLibrary::RInterpTo(CurrentRotator,DeltaRotator,DeltaSeconds,15.0f);PitchValue = FMath::ClampAngle(TargetRotator.Pitch,-90.0f,90.0f);}
}

打开动画蓝图,将瞄准偏移添加到状态机中,并用通过骨骼层混合动画。

 当向上瞄准的时候,武器和手部会向上偏移一些。

 二、射击

2.1 射击射线检测

在这里将使用从屏幕中央,也就是准星处射出一条射线去进行射线检测,判断是否射击到了物体。

在这里将BaseCharacter中的FireWeapon方法在ManCharacter中进行了重写。

ManCharacter.h

protected:virtual void BeginPlay() override;/*** 武器开火*/virtual void FireWeapon() override;/*** 获取以屏幕中心为射线检测开始点的世界位置和方向* @param StartLocation 世界位置* @param Direction 方向*/void GetScreenFireStartLocationAndDirection(FVector& StartLocation,FVector& Direction);

ManCharacter.cpp

void AManCharacter::GetScreenFireStartLocationAndDirection(FVector& StartLocation, FVector& Direction)
{if (GEngine && GEngine->GameViewport){FVector2D OutViewportSize;GEngine->GameViewport->GetViewportSize(OutViewportSize);FVector2D HalfViewportSize = FVector2D(OutViewportSize.X/2,OutViewportSize.Y/2);APlayerController* PC = UGameplayStatics::GetPlayerController(GetWorld(),0);PC->DeprojectScreenPositionToWorld(HalfViewportSize.X,HalfViewportSize.Y,StartLocation,Direction);}
}

HalfViewportSize就是屏幕中央的位置,使用DeprojectScreenPositionToWorld将屏幕坐标转化成世界坐标并获取了指向的方向。

在FireWeapon中进行射线检测:

void AManCharacter::FireWeapon()
{Super::FireWeapon();FVector OutWorldLocation;FVector OutWorldDirection;GetScreenFireStartLocationAndDirection(OutWorldLocation,OutWorldDirection);FVector StartLocation = OutWorldLocation;FVector EndLocation = StartLocation + OutWorldDirection * ShootDistance;FHitResult ScreenHitResult;FCollisionQueryParams QueryParams;QueryParams.AddIgnoredActor(this);//单通道射线检测GetWorld()->LineTraceSingleByChannel(ScreenHitResult,StartLocation,EndLocation,ECC_Visibility,QueryParams);FColor DrawColor = FColor::Red;if (ScreenHitResult.GetActor()){EndLocation = ScreenHitResult.Location;DrawColor = FColor::Green;}DrawDebugLine(GetWorld(),StartLocation,EndLocation,DrawColor,false,2.0f,0,2.0f);
}

如果在ManCharacter中重写了FireWeapon的话,要Super::FireWeapon();调用一下父类,会将父类中的FireWeapon内容执行一遍,再去往下执行。

在这里使用了一个DrawDebugLine画一条线的方式进行调试,看下是否检测到了东西,注意射线检测的通道,这里是ECC_Visibility,如果没检测到的话,是红线,检测到则是绿线。

 2.2 枪口特效

射击的时候给武器添加射击的特效

使用的方法是用SpawnEmitterAtLocation在指定位置生成的粒子特效,这里使用的是ParticleSystem特效。

武器的模型中添加一个Muzzle的插槽,提供生成的位置。

 ManCharacter.h

UPROPERTY(EditAnywhere,BlueprintReadOnly,Category=Properties,meta=(AllowPrivateAccess="true"))
UParticleSystem* MuzzleParticle;//枪口特效

ManCharacter.cpp

//枪口特效
if (MuzzleParticle)
{FTransform MuzzleTransform = WeaponMesh->GetSocketTransform("Muzzle");UGameplayStatics::SpawnEmitterAtLocation(GetWorld(),MuzzleParticle,MuzzleTransform.GetLocation(),MuzzleTransform.Rotator(),FVector(0.5f));
}

2.3  射击到物体的撞击特效

ManCharacter.h

UPROPERTY(EditAnywhere,BlueprintReadOnly,Category=Properties,meta=(AllowPrivateAccess="true"))
UParticleSystem* ImpactParticle;//枪口特效

ManCharacter.cpp

//撞击特效
if (ImpactParticle)
{UGameplayStatics::SpawnEmitterAtLocation(GetWorld(),ImpactParticle,EndLocation);
}

注意:撞击效果要放到射线检测成功处,如果没有射击到物体,不需要显示撞击特效。

2.4  射击轨道特效

射击轨道同样需要根据射击结束点来处理轨道的长短。

在轨道特效中有一个目标,其中可以使用目标命名,SetVectorParameter设置向量参数去处理。

 ManCharacter.h

UPROPERTY(EditAnywhere,BlueprintReadOnly,Category=Properties,meta=(AllowPrivateAccess="true"))
UParticleSystem* BeamParticle;//射击轨迹特效

ManCharacter.cpp

//射击轨迹特效
if (BeamParticle)
{FTransform MuzzleTransform = WeaponMesh->GetSocketTransform("Muzzle");UParticleSystemComponent* PSComp = UGameplayStatics::SpawnEmitterAtLocation(GetWorld(),BeamParticle,MuzzleTransform.GetLocation());if (PSComp){PSComp->SetVectorParameter("Target",EndLocation);}
}

 2.5 射击音效

ManCharacter.h

UPROPERTY(EditAnywhere,BlueprintReadOnly,Category=Properties,meta=(AllowPrivateAccess="true"))
USoundBase* FireSound;//射击音效

ManCharacter.cpp

//射击音效
if(FireSound)
{UGameplayStatics::PlaySoundAtLocation(GetWorld(),FireSound,GetActorLocation());
}

2.6 射击效果优化

如图所示,准星瞄准的前方有一块立方体挡住,射击落点在准星处,而实际上射击轨道是穿过了立方体,所以,此时射击落点应当设置在碰撞到立方体处的位置。

 这里修复的方式是在以准星为落击点时,进行了射击检测的时候,如果射击到物体时,再以枪口为起点,准星的落击碰撞点为终点进行射线检测,如果碰撞到的话,落击点为枪口射线检测的结果为最终落击点。

 在ManCharacter.cpp中的FireWeapon方法:

FVector OutWorldLocation;
FVector OutWorldDirection;
GetScreenFireStartLocationAndDirection(OutWorldLocation,OutWorldDirection);
FVector StartLocation = OutWorldLocation;
FVector EndLocation = StartLocation + OutWorldDirection * ShootDistance;
FHitResult ScreenHitResult;
FCollisionQueryParams QueryParams;
QueryParams.AddIgnoredActor(this);
//单通道射线检测
GetWorld()->LineTraceSingleByChannel(ScreenHitResult,StartLocation,EndLocation,ECC_Visibility,QueryParams);
if (ScreenHitResult.GetActor())
{EndLocation = ScreenHitResult.Location;//以枪口为初始点的射线检测FHitResult MuzzleHitResult;FCollisionQueryParams MuzzleQueryParams;MuzzleQueryParams.AddIgnoredActor(this);FTransform MuzzleTransform = WeaponMesh->GetSocketTransform("Muzzle");FVector MuzzleStart = MuzzleTransform.GetLocation();FVector MuzzleEnd = EndLocation;GetWorld()->LineTraceSingleByChannel(MuzzleHitResult,MuzzleStart,MuzzleEnd,ECC_Visibility,MuzzleQueryParams);if (MuzzleHitResult.GetActor()){EndLocation = MuzzleHitResult.Location;}//撞击特效if (ImpactParticle){UGameplayStatics::SpawnEmitterAtLocation(GetWorld(),ImpactParticle,EndLocation);}
}

2.7 代码重构和对应代码

2.7.1 ManCharacter.h

#pragma once#include "CoreMinimal.h"
#include "Gameplay/BaseCharacter.h"
#include "ManCharacter.generated.h"class USkeletalMeshComponent;
class UParticleSystem;
class USoundBase;/*** 小白人角色*/
UCLASS()
class SHOOTINGGAME_API AManCharacter : public ABaseCharacter
{GENERATED_BODY()public:AManCharacter();
protected:virtual void BeginPlay() override;/*** 武器开火*/virtual void FireWeapon() override;/*** 获取以屏幕中心为射线检测开始点的世界位置和方向* @param StartLocation 世界位置* @param Direction 方向*/void GetScreenFireStartLocationAndDirection(FVector& StartLocation,FVector& Direction);/*** 屏幕起始点射线检测* @param EndLocation 屏幕起始点射线检测的碰撞点* @param HitResult 碰撞结果*/void ScreenLineTrace(FVector& EndLocation,FHitResult& HitResult);/*** 枪口射线检测* @param OutLocation 输出的位置* @param ScreenHitLocation 屏幕点为起始点的射线检测碰撞点*/void MuzzleLineTrace(FVector& OutLocation,FVector ScreenHitLocation);/*** 设置开火的枪口特效,射击轨道特效,射击音效* @param TargetLocation 目标点* @param Hit 射线检测撞击结果*/void FireEffect(FVector TargetLocation,FHitResult Hit);
private:UPROPERTY(VisibleAnywhere,BlueprintReadOnly,Category=Components,meta=(AllowPrivateAccess="true"))USkeletalMeshComponent* WeaponMesh;UPROPERTY(EditAnywhere,BlueprintReadOnly,Category=Properties,meta=(AllowPrivateAccess="true"))float ShootDistance;//射击距离UPROPERTY(EditAnywhere,BlueprintReadOnly,Category=Properties,meta=(AllowPrivateAccess="true"))UParticleSystem* MuzzleParticle;//枪口特效UPROPERTY(EditAnywhere,BlueprintReadOnly,Category=Properties,meta=(AllowPrivateAccess="true"))UParticleSystem* ImpactParticle;//枪口特效UPROPERTY(EditAnywhere,BlueprintReadOnly,Category=Properties,meta=(AllowPrivateAccess="true"))UParticleSystem* BeamParticle;//射击轨迹特效UPROPERTY(EditAnywhere,BlueprintReadOnly,Category=Properties,meta=(AllowPrivateAccess="true"))USoundBase* FireSound;//射击音效
};

2.7.2 ManCharacter.cpp

#include "Gameplay/ManCharacter.h"
#include "Kismet/GameplayStatics.h"
#include "Particles/ParticleSystemComponent.h"AManCharacter::AManCharacter()
{PrimaryActorTick.bCanEverTick = true;WeaponMesh = CreateDefaultSubobject<USkeletalMeshComponent>(TEXT("WeaponMesh"));WeaponMesh->SetupAttachment(GetMesh(),"WeaponSocket");ShootDistance = 10000.0f;
}void AManCharacter::BeginPlay()
{Super::BeginPlay();
}void AManCharacter::FireWeapon()
{Super::FireWeapon();FVector OutLocation;FHitResult ScreenHitResult;//屏幕起始点射线检测ScreenLineTrace(OutLocation,ScreenHitResult);//射击效果FireEffect(OutLocation,ScreenHitResult);
}void AManCharacter::GetScreenFireStartLocationAndDirection(FVector& StartLocation, FVector& Direction)
{if (GEngine && GEngine->GameViewport){FVector2D OutViewportSize;GEngine->GameViewport->GetViewportSize(OutViewportSize);FVector2D HalfViewportSize = FVector2D(OutViewportSize.X/2,OutViewportSize.Y/2);APlayerController* PC = UGameplayStatics::GetPlayerController(GetWorld(),0);PC->DeprojectScreenPositionToWorld(HalfViewportSize.X,HalfViewportSize.Y,StartLocation,Direction);}
}void AManCharacter::ScreenLineTrace(FVector& EndLocation,FHitResult& HitResult)
{FVector OutWorldLocation;FVector OutWorldDirection;GetScreenFireStartLocationAndDirection(OutWorldLocation,OutWorldDirection);const FVector StartLocation = OutWorldLocation;EndLocation = StartLocation + OutWorldDirection * ShootDistance;FCollisionQueryParams QueryParams;QueryParams.AddIgnoredActor(this);//单通道射线检测GetWorld()->LineTraceSingleByChannel(HitResult,StartLocation,EndLocation,ECC_Visibility,QueryParams);if (HitResult.GetActor()){EndLocation = HitResult.Location;//以枪口为初始点的射线检测MuzzleLineTrace(EndLocation,EndLocation);}
}void AManCharacter::MuzzleLineTrace(FVector& OutLocation,FVector ScreenHitLocation)
{FHitResult MuzzleHitResult;FCollisionQueryParams MuzzleQueryParams;MuzzleQueryParams.AddIgnoredActor(this);FTransform MuzzleTransform = WeaponMesh->GetSocketTransform("Muzzle");FVector MuzzleStart = MuzzleTransform.GetLocation();FVector MuzzleEnd = ScreenHitLocation;GetWorld()->LineTraceSingleByChannel(MuzzleHitResult,MuzzleStart,MuzzleEnd,ECC_Visibility,MuzzleQueryParams);if (MuzzleHitResult.GetActor()){OutLocation = MuzzleHitResult.Location;}
}void AManCharacter::FireEffect(FVector TargetLocation,FHitResult Hit)
{const FTransform MuzzleTransform = WeaponMesh->GetSocketTransform("Muzzle");if (Hit.GetActor()){//撞击特效if (ImpactParticle){UGameplayStatics::SpawnEmitterAtLocation(GetWorld(),ImpactParticle,TargetLocation);}}//枪口特效if (MuzzleParticle){UGameplayStatics::SpawnEmitterAtLocation(GetWorld(),MuzzleParticle,MuzzleTransform.GetLocation(),MuzzleTransform.Rotator(),FVector(0.5f));}//射击轨迹特效if (BeamParticle){UParticleSystemComponent* PSComp = UGameplayStatics::SpawnEmitterAtLocation(GetWorld(),BeamParticle,MuzzleTransform.GetLocation());if (PSComp){PSComp->SetVectorParameter("Target",TargetLocation);}}//射击音效if(FireSound){UGameplayStatics::PlaySoundAtLocation(GetWorld(),FireSound,GetActorLocation());}
}

这篇关于射击游戏案例(四)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/998946

相关文章

Python通用唯一标识符模块uuid使用案例详解

《Python通用唯一标识符模块uuid使用案例详解》Pythonuuid模块用于生成128位全局唯一标识符,支持UUID1-5版本,适用于分布式系统、数据库主键等场景,需注意隐私、碰撞概率及存储优... 目录简介核心功能1. UUID版本2. UUID属性3. 命名空间使用场景1. 生成唯一标识符2. 数

PostgreSQL的扩展dict_int应用案例解析

《PostgreSQL的扩展dict_int应用案例解析》dict_int扩展为PostgreSQL提供了专业的整数文本处理能力,特别适合需要精确处理数字内容的搜索场景,本文给大家介绍PostgreS... 目录PostgreSQL的扩展dict_int一、扩展概述二、核心功能三、安装与启用四、字典配置方法

Python中re模块结合正则表达式的实际应用案例

《Python中re模块结合正则表达式的实际应用案例》Python中的re模块是用于处理正则表达式的强大工具,正则表达式是一种用来匹配字符串的模式,它可以在文本中搜索和匹配特定的字符串模式,这篇文章主... 目录前言re模块常用函数一、查看文本中是否包含 A 或 B 字符串二、替换多个关键词为统一格式三、提

Python get()函数用法案例详解

《Pythonget()函数用法案例详解》在Python中,get()是字典(dict)类型的内置方法,用于安全地获取字典中指定键对应的值,它的核心作用是避免因访问不存在的键而引发KeyError错... 目录简介基本语法一、用法二、案例:安全访问未知键三、案例:配置参数默认值简介python是一种高级编

MySQL中的索引结构和分类实战案例详解

《MySQL中的索引结构和分类实战案例详解》本文详解MySQL索引结构与分类,涵盖B树、B+树、哈希及全文索引,分析其原理与优劣势,并结合实战案例探讨创建、管理及优化技巧,助力提升查询性能,感兴趣的朋... 目录一、索引概述1.1 索引的定义与作用1.2 索引的基本原理二、索引结构详解2.1 B树索引2.2

从入门到精通MySQL 数据库索引(实战案例)

《从入门到精通MySQL数据库索引(实战案例)》索引是数据库的目录,提升查询速度,主要类型包括BTree、Hash、全文、空间索引,需根据场景选择,建议用于高频查询、关联字段、排序等,避免重复率高或... 目录一、索引是什么?能干嘛?核心作用:二、索引的 4 种主要类型(附通俗例子)1. BTree 索引(

HTML中meta标签的常见使用案例(示例详解)

《HTML中meta标签的常见使用案例(示例详解)》HTMLmeta标签用于提供文档元数据,涵盖字符编码、SEO优化、社交媒体集成、移动设备适配、浏览器控制及安全隐私设置,优化页面显示与搜索引擎索引... 目录html中meta标签的常见使用案例一、基础功能二、搜索引擎优化(seo)三、社交媒体集成四、移动

Python实例题之pygame开发打飞机游戏实例代码

《Python实例题之pygame开发打飞机游戏实例代码》对于python的学习者,能够写出一个飞机大战的程序代码,是不是感觉到非常的开心,:本文主要介绍Python实例题之pygame开发打飞机... 目录题目pygame-aircraft-game使用 Pygame 开发的打飞机游戏脚本代码解释初始化部

六个案例搞懂mysql间隙锁

《六个案例搞懂mysql间隙锁》MySQL中的间隙是指索引中两个索引键之间的空间,间隙锁用于防止范围查询期间的幻读,本文主要介绍了六个案例搞懂mysql间隙锁,具有一定的参考价值,感兴趣的可以了解一下... 目录概念解释间隙锁详解间隙锁触发条件间隙锁加锁规则案例演示案例一:唯一索引等值锁定存在的数据案例二:

MySQL 表的内外连接案例详解

《MySQL表的内外连接案例详解》本文给大家介绍MySQL表的内外连接,结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录表的内外连接(重点)内连接外连接表的内外连接(重点)内连接内连接实际上就是利用where子句对两种表形成的笛卡儿积进行筛选,我