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

时间:2013-07-18 11:44:24

标签: c# .net

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

首先我考虑使用反射,但反射速度太慢。我读到了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表达式而不是游戏体系结构创建闭包。目前,对于每个成员,我们想要动画,每次开始新动画时都必须写入两个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

2 个答案:

答案 0 :(得分:0)

您可以创建一个界面:

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();
    }
}

答案 1 :(得分:0)

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();