【问题标题】:UE4 - How do I get actors of an array to follow the previous actor like in Snake?UE4 - 我如何让数组的演员跟随前一个演员,就像在 Snake 中一样?
【发布时间】:2020-10-21 21:19:37
【问题描述】:

我是 C++ 新手,甚至是 UE4 新手。

我正在尝试创建一个 Snake 游戏,但我无法让蛇的身体部分像在 Snake 中那样移动。就像一列演员。如何在 Snake 游戏中让身体像火车/蛇一样移动?

我制作了一个 gif 来尝试显示问题(抱歉,如果它太小了)。Snake segment movement problem

绿色演员是蛇的头,黄色演员是产生的部分(当前当我按空格键时)。

如果有帮助,我可以发布代码片段吗?

github 仓库在这里:https://github.com/joeyisplaying/SnakeGame/tree/dev-branch/Source/SnakeGame

【问题讨论】:

  • 考虑在贪吃蛇游戏中,只有头和尾段移动。大多数身体部分实际上并没有移动,它们保持在同一个位置。所以,在一个新的位置绘制头部,用一个身体段替换旧的头部;同样,擦除尾部,然后用尾部替换最后的主体部分。

标签: c++ unreal-engine4


【解决方案1】:

已解决!对于遇到此问题的任何人,我设法在 YouTube 上的视频中找到了一个非常简单的解决方案。我的代码现在看起来像这样:

    void ASnake::UpdateTailSegmentLoc()
{
    if(!TailSegment)
    {
        return;
    }
    if(TailSegment)
    {
        for (int32 i = 0; i < TailSegmentArray.Num(); i++)
        {
            const FVector CurrentSectionLoc = TailSegmentArray[i]->GetActorLocation();
            TailSegmentArray[i]->SetActorLocation(PreviousTailSegmentLoc);
            PreviousTailSegmentLoc = CurrentSectionLoc;
        }
    }
}

勾号现在看起来像这样:

    // Called every frame
void ASnake::Tick(float DeltaTime)
{
    Super::Tick(DeltaTime);
    PreviousTailSegmentLoc = SnakeHead->GetComponentLocation();
    
    if(!MovementDirection.IsZero())
    {
        const FVector NewLocation = SnakeHead->GetRelativeLocation() + (MovementDirection * DeltaTime * SnakeHeadSpeed);
        SnakeHead->SetRelativeLocation(NewLocation);

        UpdateTailSegmentLoc();
    }
}

YouTube 视频在这里:https://www.youtube.com/watch?v=x8s86k6JUl8

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-04
    • 1970-01-01
    • 2011-11-05
    • 2016-10-20
    • 2020-04-11
    • 1970-01-01
    • 2022-11-07
    • 1970-01-01
    相关资源
    最近更新 更多