制作角色属性Comp
添加一个Actorcomp
在.h内添加生命值与减少血量的函数
protected: //只在蓝图内可以编辑,在编辑器界面不能编辑 UPROPERTY(EditDefaultsOnly,BlueprintReadOnly,Category="Attributs") float Health; // Called when the game starts // public: UFUNCTION(BlueprintCallable,Category="Attributs") bool ApplyHealthChange(float Delta); // Called every frame // };
在.cpp内绑定变量与添加减少血量的void
USAttributeComponent::USAttributeComponent() { // Health = 100; // ... } bool USAttributeComponent::ApplyHealthChange(float Delta) { Health += Delta; return true; }
在角色的.h和.cpp内绑定这个actorcomp
.h
//角色属性 UPROPERTY(VisibleAnywhere,BlueprintReadOnly,Category="Components") USAttributeComponent * AttributeComp;
.cpp
//将创建的AttributeComp绑定在角色上 AttributeComp = CreateDefaultSubobject<USAttributeComponent>("AttributeComp");
修改魔法子弹的.h,添加一个void
UFUNCTION() void OnActorOverlap(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult);
.cpp
void ASMagicProjectile::OnActorOverlap(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult) { if(OtherActor) { //注意是GetComponentByClass不是GetComponentsByClass USAttributeComponent* AttributeComp = Cast<USAttributeComponent>(OtherActor->GetComponentByClass(USAttributeComponent::StaticClass())); if(AttributeComp) { AttributeComp->ApplyHealthChange(-20.0f); Destroy(); } } }
最后修改碰撞选项
创建一个生命值的UMG
首先添加Canvas Panel,然后添加Horizontal Box,再添加ProgressBar和Text
在ProgressBar的Slot -> Size处改为Fill
在Text的Content ->Text处新建一个Binding
函数为接受之前创建的AttributeComponent的Float Health值
效果图:
受到子弹攻击会减少HP的数值