我正在尝试为我的游戏引擎编写动画组件。动画组件必须修改(动画)任何游戏对象的任何成员的值。问题是成员通常是值类型,但动画组件需要对它们进行某种引用才能更改它。
首先我想到了使用反射,但是反射太慢了。我读到了 C# 中可能有帮助的其他技术(指针、Reflection.Emit、表达式树、动态方法/对象、委托、lambda 表达式、闭包......)但我不知道这些东西足够好,能够解决问题。
动画组件将具有能够获取和存储对随机对象成员的引用并随时间动画其值的方法。像这样:StartSomeAnimation(ref memberToAnimate)
会有其他参数(如动画长度),但问题在于传递成员。需要存储对memberToAnimate的引用(即使它是值类型),以便动画组件每帧都可以更新它。
我能够自己解决的最接近的解决方案是使用 lambda 表达式和 Action<> Func<> 委托(参见下面的示例)。它比直接更改成员+更多垃圾分配慢约 4 倍。但是我仍然无法像上面的示例那样制作如此简单的方法签名。
class Program
{
static void Main(string[] args)
{
GameItem g = new GameItem();
Console.WriteLine("Initialized to:" + g.AnimatedField);
g.StartSomeAnimation();
// NOTE: in real application IntializeAnim method would create new animation object
// and add it to animation component that would call update method until
// animation is complete
Console.WriteLine("Animation started:" + g.AnimatedField);
Animation.Update();
Console.WriteLine("Animation update 1:" + g.AnimatedField);
Animation.Update();
Console.WriteLine("Animation update 2:" + g.AnimatedField);
Animation.Update();
Console.WriteLine("Animation update 3:" + g.AnimatedField);
Console.ReadLine();
}
}
class GameItem
{
public int AnimatedField;// Could be any member of any GameItem class
public void StartSomeAnimation()
{
// Question: can creation of getter and setter be moved inside the InitializeAnim method?
Animation.IntializeAnim(
() => AnimatedField, // return value of our member
(x) => this.AnimatedField = x); // set value of our member
}
}
class Animation // this is static dumb class just for simplicity's sake
{
static Action<int> setter;
static Func<int> getter;
// works fine, but we have to write getters and setters each time we start an animation
public static void IntializeAnim(Func<int> getter, Action<int> setter)
{
Animation.getter = getter;
Animation.setter = setter;
}
// Ideally we would need to pass only a member like this,
// but we get an ERROR: cannot use ref or out parameter inside an anonymous method lambda expression or query expression
public static void IntializeAnim(ref int memberToAnimate)
{
Animation.getter = () => memberToAnimate;
Animation.setter = (x) => memberToAnimate = x;
}
public static void Update()
{
// just some quick test code that queries and changes the value of a member that we animate
int currentValue = getter();
if (currentValue == 0)
{
currentValue = 5;
setter(currentValue);
}
else
setter(currentValue + currentValue);
}
}
编辑:添加了一个更完整的示例,希望使问题更清楚一些。请关注如何使用 lambda 表达式创建闭包,而不是游戏架构。目前对于每个成员,我们想要动画,每次我们开始一个新的动画(IntializeAnim方法)时都必须编写两个 lambda 表达式。启动动画可以简化吗?看看IntializeAnim
当前是如何调用方法的。
class Program
{
static bool GameRunning = true;
static void Main(string[] args)
{
// create game items
Lamp lamp = new Lamp();
GameWolrd.AddGameItem(lamp);
Enemy enemy1 = new Enemy();
Enemy enemy2 = new Enemy();
GameWolrd.AddGameItem(enemy1);
GameWolrd.AddGameItem(enemy2);
// simple game loop
while (GameRunning)
{
GameWolrd.Update();
AnimationComponent.Update();
}
}
}
static class GameWolrd
{
static List<IGameItem> gameItems;
public static void Update()
{
for (int i = 0; i < gameItems.Count; i++)
{
IGameItem gameItem = gameItems[i];
gameItem.Update();
}
}
public static void AddGameItem(IGameItem item)
{
gameItems.Add(item);
}
}
static class AnimationComponent
{
static List<IAnimation> animations;
public static void Update()
{
for (int i = 0; i < animations.Count; i++)
{
IAnimation animation = animations[i];
if (animation.Parent == null ||
animation.Parent.IsAlive == false ||
animation.IsFinished)
{// remove animations we don't need
animations.RemoveAt(i);
i--;
}
else // update animation
animation.Update();
}
}
public static void AddAnimation(IAnimation anim)
{
animations.Add(anim);
}
}
interface IAnimation
{
void Update();
bool IsFinished;
IGameItem Parent;
}
/// <summary>
/// Game items worry only about state changes.
/// Nice state transitions/animations logics reside inside IAnimation objects
/// </summary>
interface IGameItem
{
void Update();
bool IsAlive;
}
#region GameItems
class Lamp : IGameItem
{
public float Intensity;
public float ConeRadius;
public bool IsAlive;
public Lamp()
{
// Question: can be creation of getter and setter moved
// inside the InitializeAnim method?
SineOscillation.IntializeAnim(
() => Intensity, // getter
(x) => this.Intensity = x,// setter
parent: this,
max: 1,
min: 0.3f,
speed: 2);
// use same animation algorithm for different member
SineOscillation.IntializeAnim(
() => ConeRadius, // getter
(x) => this.ConeRadius = x,// setter
parent: this,
max: 50,
min: 20f,
speed: 15);
}
public void Update()
{}
}
class Enemy : IGameItem
{
public float EyesGlow;
public float Health;
public float Size;
public bool IsAlive;
public Enemy()
{
Health = 100f;
Size = 20;
// Question: can creation of getter and setter be moved
// inside the InitializeAnim method?
SineOscillation.IntializeAnim(
() => EyesGlow, // getter
(x) => this.EyesGlow = x,// setter
parent: this,
max: 1,
min: 0.5f,
speed: 0.5f);
}
public void Update()
{
if (GotHitbyPlayer)
{
DecreaseValueAnimation.IntializeAnim(
() => Health, // getter
(x) => this.Health = x,// setter
parent: this,
amount: 10,
speed: 1f);
DecreaseValueAnimation.IntializeAnim(
() => Size, // getter
(x) => this.Size = x,// setter
parent: this,
amount: 1.5f,
speed: 0.3f);
}
}
}
#endregion
#region Animations
public class SineOscillation : IAnimation
{
Action<float> setter;
Func<float> getter;
float max;
float min;
float speed;
bool IsFinished;
IGameItem Parent;
// works fine, but we have to write getters and setters each time we start an animation
public static void IntializeAnim(Func<float> getter, Action<float> setter, IGameItem parent, float max, float min, float speed)
{
SineOscillation anim = new SineOscillation();
anim.getter = getter;
anim.setter = setter;
anim.Parent = parent;
anim.max = max;
anim.min = min;
anim.speed = speed;
AnimationComponent.AddAnimation(anim);
}
public void Update()
{
float calcualtedValue = // calculate value using sine formula (use getter if necessary)
setter(calcualtedValue);
}
}
public class DecreaseValueAnimation : IAnimation
{
Action<float> setter;
Func<float> getter;
float startValue;
float amount;
float speed;
bool IsFinished;
IGameItem Parent;
// works fine, but we have to write getters and setters each time we start an animation
public static void IntializeAnim(Func<float> getter, Action<float> setter, IGameItem parent, float amount, float speed)
{
DecreaseValueAnimation anim = new DecreaseValueAnimation();
anim.getter = getter;
anim.setter = setter;
anim.Parent = parent;
anim.amount = amount;
anim.startValue = getter();
anim.speed = speed;
AnimationComponent.AddAnimation(anim);
}
public void Update()
{
float calcualtedValue = getter() - speed;
if (calcualtedValue <= startValue - amount)
{
calcualtedValue = startValue - amount;
this.IsFinished = true;
}
setter(calcualtedValue);
}
}
#endregion