【虚幻引擎5 II】简单的射线追踪

【虚幻引擎5 II】简单的射线追踪

anzai249 床主

原理

灵魂画师上线!

很多游戏像CS:GO子弹都是从玩家眼睛里以一条直线打出去的,而不是从枪里。

所以我们只要从屏幕中心或玩家眼睛向外射线,然后在地图里定位这个交点即可实现瞄准。

代码

1
2
3
// CombatComponent.h
// 先定义
void TraceUnderCrosshairs(FHitResult& TraceHitResult);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// CombatComponent.cpp
#include "Kismet/GameplayStatics.h" // 包含把客户端屏幕坐标转换为场景里坐标的function。
#include "DrawDebugHelpers.h" // 用于显示Debug盒子

void UCombatComponent::TraceUnderCrosshairs(FHitResult& TraceHitResult)
{
FVector2D ViewportSize;
if (GEngine && GEngine->GameViewport)
{
GEngine->GameViewport->GetViewportSize(ViewportSize);
} // 获取屏幕大小

FVector2D CrosshairLocation(ViewportSize.X / 2.f, ViewportSize.Y / 2.f); // 定位屏幕中心
FVector CrosshairWorldPosition;
FVector CrosshairWorldDirection;
bool bScreenToWorld = UGameplayStatics::DeprojectScreenToWorld(
UGameplayStatics::GetPlayerController(this, 0),
CrosshairLocation,
CrosshairWorldPosition,
CrosshairWorldDirection
); // 将屏幕中心的位置转换到地图中

if (bScreenToWorld)
{
FVector Start = CrosshairWorldPosition;

FVector End = Start + CrosshairWorldDirection * TRACE_LENGTH; // TRACE_LENGTH 是射线长度,我define的是80000.f

GetWorld()->LineTraceSingleByChannel(
TraceHitResult,
Start,
End,
ECollisionChannel::ECC_Visibility
); // 发出射线,遇到可见物体时便停止

if (!TraceHitResult.bBlockingHit)
{
TraceHitResult.ImpactPoint = End;
}
else
{
DrawDebugSphere(
GetWorld(),
TraceHitResult.ImpactPoint,
12.f,
12,
FColor::Red
);
} // 画debug球,使瞄准位置可视
}
}

// 最后让它一直Tick就好了

完成

这下我们就可以看到开枪后我们可以打到地图的哪里了。

有个小问题就是这样可以打到自己,之后再修复吧。

  • 标题: 【虚幻引擎5 II】简单的射线追踪
  • 作者: anzai249
  • 创建于 : 2023-07-12 17:44:03
  • 更新于 : 2025-05-03 12:29:55
  • 链接: https://anzai.sleepingbed.top/archives/posts/ef2e4bdf.html
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
评论
Nickname
Email
Website
0/500
  • OωO
  • |´・ω・)ノ
  • ヾ(≧∇≦*)ゝ
  • (☆ω☆)
  • (╯‵□′)╯︵┴─┴
  •  ̄﹃ ̄
  • (/ω\)
  • ∠( ᐛ 」∠)_
  • (๑•̀ㅁ•́ฅ)
  • →_→
  • ୧(๑•̀⌄•́๑)૭
  • ٩(ˊᗜˋ*)و
  • (ノ°ο°)ノ
  • (´இ皿இ`)
  • ⌇●﹏●⌇
  • (ฅ´ω`ฅ)
  • (╯°A°)╯︵○○○
  • φ( ̄∇ ̄o)
  • ヾ(´・ ・`。)ノ"
  • ( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
  • (ó﹏ò。)
  • Σ(っ °Д °;)っ
  • ( ,,´・ω・)ノ"(´っω・`。)
  • ╮(╯▽╰)╭
  • o(*////▽////*)q
  • >﹏<
  • ( ๑´•ω•) "(ㆆᴗㆆ)
  • 😂
  • 😀
  • 😅
  • 😊
  • 🙂
  • 🙃
  • 😌
  • 😍
  • 😘
  • 😜
  • 😝
  • 😏
  • 😒
  • 🙄
  • 😳
  • 😡
  • 😔
  • 😫
  • 😱
  • 😭
  • 💩
  • 👻
  • 🙌
  • 🖕
  • 👍
  • 👫
  • 👬
  • 👭
  • 🌚
  • 🌝
  • 🙈
  • 💊
  • 😶
  • 🙏
  • 🍦
  • 🍉
  • 😣
  • 颜文字
  • Emoji
  • Bilibili
0 comments
No comment
目录
【虚幻引擎5 II】简单的射线追踪