2

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

首先我想到了使用反射,但是反射太慢了。我读到了 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
4

2 回答 2

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 原则的信息。

升级版:

另一种选择是让项目知道如何为自己设置动画:

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();
    }
}
于 2013-07-18T12:05:02.373 回答
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();
于 2013-07-18T12:30:22.683 回答