游戏引擎 / 系统课时
管理武器与拾取物
管理武器与拾取物
武器系统最容易失控的地方不是开火,而是同一件物品在世界、背包和手持状态之间反复切换。本节先建立最小物品生命周期,再用一个库存组件完成拾取、装备、切换和丢弃,避免碰撞、物理和可见性互相打架。
学习目标
- 建立世界物品、收纳物品与已装备物品之间的状态转换
- 实现拾取、装备、切换和丢弃的最小 C++ 链路
- 验证附着、碰撞、物理模拟和库存索引始终保持一致
把物品状态收敛到少数转换
一个基础武器只需要三个可观察状态:在世界中时可碰撞并可被拾取;进入库存后关闭碰撞和物理并隐藏;装备后仍关闭物理,但附着到角色骨骼网格的武器插槽并显示。丢弃则从角色分离,重新开启世界碰撞和物理。

这个模型的关键是把状态切换集中到武器自己的 Store、Equip、Drop 方法里。库存组件只决定当前是哪一把,不直接到处修改 Mesh 的碰撞或物理属性。
实现拾取、装备、切换和丢弃
下面是片段示例,放入已有 UE 5 C++ 项目。角色的 Skeletal Mesh 需要存在名为 WeaponSocket 的 Socket;项目模块导出宏 YOURGAME_API 也要替换成实际名称。交互射线命中武器时调用 Pickup,输入动作分别调用 SwitchNext 与 DropCurrent。
cpp
// WeaponActor.h
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "WeaponActor.generated.h"
class UStaticMeshComponent;
class USceneComponent;
UCLASS()
class YOURGAME_API AWeaponActor : public AActor
{
GENERATED_BODY()
public:
AWeaponActor();
void Store();
void Equip(USceneComponent* Parent, FName SocketName);
void Drop(const FVector& Impulse);
private:
UPROPERTY(VisibleAnywhere)
TObjectPtr<UStaticMeshComponent> Mesh;
};
// WeaponActor.cpp
#include "WeaponActor.h"
#include "Components/StaticMeshComponent.h"
AWeaponActor::AWeaponActor()
{
Mesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Mesh"));
SetRootComponent(Mesh);
}
void AWeaponActor::Store()
{
DetachFromActor(FDetachmentTransformRules::KeepWorldTransform);
Mesh->SetSimulatePhysics(false);
SetActorEnableCollision(false);
SetActorHiddenInGame(true);
}
void AWeaponActor::Equip(USceneComponent* Parent, FName SocketName)
{
if (!Parent) return;
Mesh->SetSimulatePhysics(false);
SetActorEnableCollision(false);
SetActorHiddenInGame(false);
AttachToComponent(
Parent,
FAttachmentTransformRules::SnapToTargetNotIncludingScale,
SocketName
);
}
void AWeaponActor::Drop(const FVector& Impulse)
{
DetachFromActor(FDetachmentTransformRules::KeepWorldTransform);
SetActorHiddenInGame(false);
SetActorEnableCollision(true);
Mesh->SetSimulatePhysics(true);
Mesh->AddImpulse(Impulse, NAME_None, true);
}
// WeaponInventoryComponent.h
#pragma once
#include "CoreMinimal.h"
#include "Components/ActorComponent.h"
#include "WeaponInventoryComponent.generated.h"
class AWeaponActor;
UCLASS(ClassGroup=(Inventory), meta=(BlueprintSpawnableComponent))
class YOURGAME_API UWeaponInventoryComponent : public UActorComponent
{
GENERATED_BODY()
public:
UFUNCTION(BlueprintCallable)
bool Pickup(AWeaponActor* Weapon);
UFUNCTION(BlueprintCallable)
void SwitchNext();
UFUNCTION(BlueprintCallable)
void DropCurrent();
private:
void EquipIndex(int32 NewIndex);
UPROPERTY()
TArray<TObjectPtr<AWeaponActor>> Weapons;
int32 CurrentIndex = INDEX_NONE;
FName EquipSocketName = TEXT("WeaponSocket");
};
// WeaponInventoryComponent.cpp
#include "WeaponInventoryComponent.h"
#include "WeaponActor.h"
#include "GameFramework/Character.h"
bool UWeaponInventoryComponent::Pickup(AWeaponActor* Weapon)
{
if (!IsValid(Weapon) || Weapons.Contains(Weapon)) return false;
Weapons.Add(Weapon);
Weapon->SetOwner(GetOwner());
Weapon->Store();
if (CurrentIndex == INDEX_NONE)
{
EquipIndex(0);
}
return true;
}
void UWeaponInventoryComponent::EquipIndex(int32 NewIndex)
{
ACharacter* Character = Cast<ACharacter>(GetOwner());
if (!Character || !Weapons.IsValidIndex(NewIndex)) return;
if (Weapons.IsValidIndex(CurrentIndex))
{
Weapons[CurrentIndex]->Store();
}
CurrentIndex = NewIndex;
Weapons[CurrentIndex]->Equip(Character->GetMesh(), EquipSocketName);
}
void UWeaponInventoryComponent::SwitchNext()
{
if (Weapons.Num() < 2) return;
EquipIndex((CurrentIndex + 1) % Weapons.Num());
}
void UWeaponInventoryComponent::DropCurrent()
{
if (!Weapons.IsValidIndex(CurrentIndex)) return;
const int32 DroppedIndex = CurrentIndex;
AWeaponActor* Weapon = Weapons[DroppedIndex];
Weapons.RemoveAt(DroppedIndex);
CurrentIndex = INDEX_NONE;
Weapon->SetOwner(nullptr);
Weapon->Drop(GetOwner()->GetActorForwardVector() * 250.0f);
if (!Weapons.IsEmpty())
{
EquipIndex(FMath::Min(DroppedIndex, Weapons.Num() - 1));
}
}预期结果:第一次拾取的武器自动装备到 WeaponSocket;继续拾取只加入库存;拥有至少两把武器时调用 SwitchNext 会隐藏旧武器并显示、附着新武器;调用 DropCurrent 后当前武器从库存移除,在角色前方恢复物理状态。
text
Pickup first weapon -> inventory=1, current=0, equipped
Pickup second weapon -> inventory=2, current=0
SwitchNext -> inventory=2, current=1, equipped
DropCurrent -> inventory=1, current=0, dropped weapon in world验证物理、碰撞与索引
在 PIE 中至少验证四件事:拾取后武器不能继续挡住角色;切换时场景中只显示当前武器;丢弃后武器重新出现在世界并能产生物理运动;连续丢弃到库存为空时再次切换或丢弃不会越界。
这个实现故意把弹药、伤害和开火排除在外,只固定物品生命周期。多人游戏还需要把拾取、装备和丢弃放到服务端权威逻辑中并复制状态,但单机或本地原型先保证这四个转换一致,后续扩展才不会建立在混乱的物品状态上。
按自己的节奏,确认真正理解。