简化为动画目的创建对对象成员的引用

本文关键字:对象 成员 引用 创建 动画 | 更新日期: 2023-09-27 18:23:56

我正在尝试为我的游戏引擎编写动画组件。动画组件必须修改(动画)任何游戏对象的任何成员的值。问题是,成员通常是值类型,但动画组件需要对它们进行某种引用,才能更改它

首先,我考虑使用反射,但反射太慢。我读过C#中可能有帮助的其他技术(指针、反射.发射、表达式树、动态方法/对象、委托、lambda表达式、闭包…),但我对这些技术的了解还不够好,无法解决问题。

动画组件将具有能够获取和存储对随机对象成员的引用的方法,并随着时间的推移为其值设置动画。像这样:StartSomeAnimation(ref memberToAnimate)还有其他参数(如动画长度),但问题在于传递成员。需要存储对memberToAnimate的引用(即使它是值类型),以便动画组件可以在每帧更新它。

我自己最接近解决方案的方法是使用lambda表达式和Action<>函数<>代表(请参阅下面的示例)。它大约比直接更改成员慢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表达式创建闭包,而不是游戏架构。目前,我们想要为每个成员设置动画,每次启动新动画时都必须编写两个lambda表达式(IntializeAnim方法)启动动画可以简化吗看看当前是如何调用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

简化为动画目的创建对对象成员的引用

您可以创建一个接口:

interface IGameItem
{
    int AnimatedField { get; set; }
}
class GameItem : IGameItem
{
    public int AnimatedField { get; set; }
}
class Animation
{
    public IGameItem Item { get; set; }
    public void Update()
    {
        if (Item.AnimatedField == 0)
        {
            Item.AnimatedField = 5;
        }
        else
        {
            Item.AnimatedField = Item.AnimatedField + Item.AnimatedField;
        }
    }
}

运行你的超级动画引擎将看起来像:

class Program
{
    static void Main(string[] args)
    {
        GameItem g = new GameItem() { AnimatedField = 1 };
        Animation a = new Animation() { Item = g };
        a.Update();
        Console.WriteLine(g.AnimatedField);
        a.Update();
        Console.WriteLine(g.AnimatedField);
        a.Update();
        Console.WriteLine(g.AnimatedField);
        Console.ReadLine();
    }
}

然而,请注意,为每个人揭露公共设置者并不是一个好的做法。每个类都必须提供一个被它充分使用的接口。阅读接口分离原则和其他SOLID原则。

UPD:

另一种选择是让物品知道如何制作自己的动画:

interface IAnimatable
{
    void Animate();
}
class IntegerItem : IAnimatable
{
    int _n;
    public IntegerItem(int n)
    {
        _n = n;
    }
    public void Animate()
    {
        Console.WriteLine(_n);
    }
}
class AnimationSequencer
{
    public void Update(IAnimatable item)
    {
        item.Animate();
    }
}
public static class Animation
{
    public static void Initialize(object element)
    {
        //// initialize code
    }
    public static void Update(object element)
    {
        //// update code
    }
}
public class GameItem : Animatable
{
    public GameItem(object memberToAnimate)
    {
        this.MemberToAnimate = memberToAnimate;
    }      
}
public class Animatable
{
    public object MemberToAnimate { get; set; }
    public virtual void Initialize()
    {
        Animation.Initialize(this.MemberToAnimate);
    }
    public virtual void Update()
    {
        Animation.Update(this.MemberToAnimate);
    }
}

因此,代码将是:

var gameItem = new GameItem(yourObjectToAnimate);
gameItem.Initialize();
gameItem.Update();
相关文章: