简单的处理游戏的属性问题

通常游戏中的单位/角色包含多个属性,比如生命值,移动速度,攻击力等等,游戏运行过程对属性修改非常频繁,
比如获得一个增益效果:角色基础血量提高10%,持续20秒;获得一个减益效果:最终血量降低100点,持续15秒。
为了统一描述属性,方便修改和回退属性,对于每个字段设计5个值,分别为基础值,基础增加,基础百分比增加,最终增加,最终增加百分比
格式如下:

当前值(最终值)=(((基础值 + 基础增加) * (100 + 基础增加百分比) * 0.01) + 最终增加) * (100 + 最终增加百分比) * 0.01

代码如下:


// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "CoreMinimal.h"
#include "UObject/NoExportTypes.h"
#include "AttributeSystem.generated.h"


class FAttributeValue
{

public:
	enum EValueType
	{
		VT_None = 0,
		VT_BaseValue,
		VT_BaseAdd,
		VT_BaseMultiply,
		VT_FinalAdd,
		VT_FinalMultiply,
		VT_FinalValue,

		VT_Num
	};

	FAttributeValue(int32 InBaseVal = 0)
	{
		Value.SetNum(VT_Num);
		Value[VT_BaseValue] = InBaseVal;
	}

	FORCEINLINE int32 ModifyValue(EValueType InType, int32 InValue)
	{
		Value[InType] += InValue;

		Value[VT_FinalValue] = (((Value[VT_BaseValue] 
			+ Value[VT_BaseAdd]) * (100 + Value[VT_BaseMultiply]) * 0.01f) 
			+ Value[VT_FinalAdd]) * (100 + Value[VT_FinalMultiply]) * 0.01f;

		return Value[VT_FinalValue];
	}

	FORCEINLINE int32 GetValue(EValueType InType) const
	{
		return Value[InType];
	}

protected:

	TArray<int32> Value;
};


/**
 * 
 */
UCLASS()
class UAttributeSystem : public UObject
{
	GENERATED_BODY()

public:

	UFUNCTION(BlueprintCallable)
		bool AddAttribute(int32 InKey, int32 InBaseValue)
	{
		if (GetAttribute(InKey))
		{
			return false;
		}

		AttributeList.Add(InKey, FAttributeValue(InBaseValue));

		return true;
	}

	FAttributeValue* GetAttribute(int32 InKey)
	{
		return AttributeList.Find(InKey);
	}

	int32 ModifyAttribute(int32 InKey, FAttributeValue::EValueType InType, int32 InVal)
	{
		FAttributeValue* ExistAttr = GetAttribute(InKey);
		return ExistAttr ? ExistAttr->ModifyValue(InType, InVal) : 0;
	}

protected:

	TMap<int32, FAttributeValue> AttributeList;

};

posted @ 2020-04-03 18:24  剑过不留痕残月分断魂  阅读(393)  评论(0编辑  收藏  举报