虚幻引擎ue在世界中创建物品(Actor)

我们学习ue 都知道,它可以通过虚幻引擎编辑器,直接将一个Actor 蓝图类 拖入世界中,但是我们如何用c++代码来实现这一点呢。

虚幻官方文档其实已经有说明了

https://docs.unrealengine.com/4.27/en-US/ProgrammingAndScripting/SpawnAndDestroyActors/

不过我还是来简单明了一下

关键函数就是  SpawnActor<T>()

它是UWorld类里面的东西  

我们来看看官方文档

12acb1c36de9425e87abb5d3c32a4221.jpg

 我们可以看到有7个这个名字的函数

5个模板函数,2个普通函数 用哪一个?

来看看官方文档使用的例子:

GetWorld()->SpawnActor<AActorToSpawn>(SpawnLocation,SpawnRotation);

模板函数 且两个参数

分析一下  应该是上述第四个

2dc3f6daf7bd4497be404cfdbe252e7c.jpg

 字面意思来看  第一个参数是位置的向量 第二个叫什么旋转向量  都是在世界空间的  这里面要扯到矩阵数学了  先不管 这个就是你要在世界生成的位置  和 物品方向

来看第三个参数

FActorSpawnParametersStruct

官方文档的解释是

傳遞給 SpawnActor 函數的可選參數的結果

啥意思呢  我们还是去看看详细

271eb238071c4a00b1fc2f5a4bcd630b.jpg

东西很多  比如生成时的物理碰撞问题  就类似于这个东西

GetWorld()->SpawnActor<AActorToSpawn>(SpawnLocation,SpawnRotation);

关键就是

SpawnActor<物品类>(物品在世界位置,物品在的世界方向);

如我们设置一个输入映射  

PlayerInputComponent->BindAction("SpawnActors", IE_Pressed, this, &ASpawnDestroyCppCharacter::SpawnActors);

    PlayerInputComponent->BindAction("DestroyActors", IE_Pressed, this, &ASpawnDestroyCppCharacter::DestroyActors);

}

17a4957bdcfb4a6b89266055cf0030dd.jpg

 按 1  就会调用 ASpawnDestroyCppCharacter::SpawnActors()这个函数

按2 就会调用

ASpawnDestroyCppCharacter::DestroyActors()这个函数

函数实现:

void ASpawnDestroyCppCharacter::SpawnActors()

{

 GetWorld()->SpawnActor<物品类>(物品在世界位置,物品在的世界方向);

}

void ASpawnDestroyCppCharacter::DestroyActors()

{

    TArray<AActor*> FoundActors; 保存当前运行在世界中的 actor

    UGameplayStatics::GetAllActorsOfClass(GetWorld(), 物品类::StaticClass(), FoundActors);

    for (AActor* ActorFound :FoundActors)

    {

        ActorFound->Destroy();   这是销毁actor

    }

}

函数解释

UGameplayStatics::GetAllActorsOfClass()

查找世界中指定類別的所有 Actor。 這是一個緩慢的操作,請謹慎使用,例如 不要使用每一幀。

也就是说 这东西是查找相同类的actor的

GetWorld() 获取世界 

StaticClass() 返回一個在運行時表示此類的 UClass 對象  人话就是 返回actor 的类类型

TArray<AActor*> FoundActors;

保存世界里符合当前指定actor 类型的所有actor 对象

UGameplayStatics::GetAllActorsOfClass(GetWorld(), 物品类::StaticClass(), 保存存在在世界里的当前类型的actor的数组);

UGameplayStatics::GetAllActorsOfClass 这个就可以让我们  找到一个世界里摆放的物品  然后根据这个物品的位置,旋转  来相对位置生成我们需要的actor 类

总结

在世界中生成actor    SpawnActor<物品类>()

GetWorld()->SpawnActor<物品类>(物品在世界位置,物品在的世界方向);

在世界中销毁actor      Destroy()

TArray<AActor*> FoundActors; 保存当前运行在世界中的 actor

UGameplayStatics::GetAllActorsOfClass(GetWorld(), 物品类::StaticClass(), FoundActors);

    for (AActor* ActorFound :FoundActors)

    {

        ActorFound->Destroy();   这是销毁actor

    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值