作者cjcat2266 (CJ Cat)
看板GameDesign
标题Re: [程式] 游戏程式:批次逻辑的时域切割 (更正翻译)
时间Tue Sep 5 08:39:45 2017
※ 引述《cjcat2266 (CJ Cat)》之铭言:
: 原文连结 http://wp.me/p4mzke-14V
: 动画生成原始码 https://github.com/TheAllenChou/timeslicing
: 游戏程式系列文 http://allenchou.net/game-programming-series/
最近遇到并解决时域切割的一个陷阱
在此跟大家分享一下
用判定NPC是否能看到玩家当作例子
演算法本体就是每个NPC的眼睛到玩家的射线投射(raycast)
这个运算不便宜,且几个frame的视觉逻辑层延迟不容易被玩家感觉到
所以非常适合时域切割
如果你的NPC视觉API设计只是单纯的存"代表可否看到玩家的bool值"
那基本上不会有什麽问题
void ProcessResults()
{
for (int i = 0; i < m_batchSize; ++i)
{
const BatchResult &result = batchResults[i];
npcCanSeePlayer[result.iNpc] = result.canSeePlayer;
}
}
bool CanNpcSeePlayer(int iNpc)
{
return npcCanSeePlayer[i];
}
但是如果你的NPC视觉API提供跟时间有关的存取介面
例如"过去X秒之内NPC是否可以看见玩家",那就要注意一下了
直觉上的实作方式是这样
void ProcessResults()
{
for (int i = 0; i < m_batchSize; ++i)
{
const BatchResult &result = batchResults[i];
if (result.canSeePlayer)
{
lastNpcSawPlayerTime[result.iNpc] = GetTime();
}
}
}
bool CanNpcSeePlayer(int Npc, Time timeWindow)
{
return GetTime() - lastNpcSawPlayerTime[iNpc] <= timeWindow;
}
但其实有个致命的缺点
要是刚好NPC数量多到时域切割的一个循环比timeWindow还要长
那呼叫CanNpcSeePlayer有可能会得到false negative
像询问"过去1.0秒期间NPC是否有看见玩家"
但是刚好当时NPC比较多,时域切割循环需要1.1秒
刚好在循环进度介於1.0秒和1.1之间呼叫CanNpcSeePlayer就会得到false
即使true才是正确结果
强制实施最长时域切割循环时间不失为个解决方式
但是只要timeWindow够短,永远会有上述的问题
所以比较有弹性的解决方式,是处理运算解果的时候同时记录时间
在询问结果的时候,额外检查最後一次true结果时间是否等於处理结果的时间
如果是的话,不管timeWindow一律回传结果为true
void ProcessResults()
{
for (int i = 0; i < m_batchSize; ++i)
{
const BatchResult &result = batchResults[i];
if (result.canSeePlayer)
{
lastNpcSawPlayerTime[result.iNpc] = GetTime();
}
// record time of results processing as well
lastResultsProcessedTime[result.iNpc] = GetTime();
}
}
bool CanNpcSeePlayer(int Npc, Time timeWindow)
{
const bool lastResultTrue =
lastResultsProcessedTime[iNpc].IsValid()
&& lastResultsProcessedTime[iNpc] == lastNpcSawPlayerTime[iNpc];
if (lastResultTrue)
return true;
return GetTime() - lastNpcSawPlayerTime[iNpc] <= timeWindow;
}
时域切割循环时间自然是越短越理想
但是总是有询问结果的timeWindow过短的可能性
用这个方式可以预防错误的结果
--
Web
http://AllenChou.net
Twitter
http://twitter.com/TheAllenChou
LinkedIn
http://linkedin.com/in/MingLunChou
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 104.174.112.138
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/GameDesign/M.1504571987.A.232.html
※ 编辑: cjcat2266 (104.174.112.138), 09/05/2017 08:41:28
1F:推 dreamnook: 推 09/05 09:31
2F:推 Frostx: 推 09/09 09:41