使用与Awful nested timers, how do I refactor?相同的代码,尽管这个问题与我提出新问题的程度大不相同。
基本上,我有一系列'运动'类,我想在彼此之后“运行”它们;当他们全部完成时,我想最终将图像设置为特定的东西。
我在考虑使用foreach循环,然后在foreach结束之前放一个计时器才能继续?我不能让它工作。有人可以帮助我,我如何让这个方法可以随时使用我想要的“动作”列表?
我想要的是一个方法
public void SetPlayerAnimation(int location, string endsprite, params Movement[] parts)
{
//Get the sprite object to be animated
TranslateTarget = "Sprite" + location.ToString();
OnPropertyChanged("TranslateTarget");
...stuff here that can have as many 'Movement parts' as are passed along.
...and waits with the next iteration until the previous one is done.
...but doesn't spin around in this method, so preferably using events, maybe?
//End with a final sprite
SetPlayerSprite(location, endsprite);
}
我所拥有的是以下代码。
//Three part animation
public void SetPlayerAnimation(int location, string endsprite, Movement part1, Movement part2, Movement part3)
{
//Get the sprite object to be animated
TranslateTarget = "Sprite" + location.ToString();
OnPropertyChanged("TranslateTarget");
//Start first part
part1.Run(location);
//Wait till its done to start the second part.
var timer = new DispatcherTimer();
timer.Interval = part1.duration;
timer.Start();
timer.Tick += (s, args) =>
{
//Start second part
part2.Run(location);
timer.Stop();
//Wait till its done to start the third part.
var timer2 = new DispatcherTimer();
timer2.Interval = part2.duration;
timer2.Start();
timer2.Tick += (s2, args2) =>
{
//Start third part
part3.Run(location);
timer2.Stop();
//When we're through all parts, wait till its done and set the endsprite.
var timer3 = new DispatcherTimer();
timer3.Interval = part3.duration;
timer3.Start();
timer3.Tick += (s3, args3) =>
{
//End with a final sprite
SetPlayerSprite(location, endsprite);
timer3.Stop();
};
};
};
}
答案 0 :(得分:0)
也许你可以尝试这样的事情:
private void RepetitionRoutine(Movement part, Action next, int location)
{
part.Run(location);
var timer = new DispatcherTimer();
timer.Interval = part.duration;
timer.Start();
timer.Tick += (s, args) =>
{
next();
timer.Stop();
}
}
public class MovementChain
{
Action _next;
Movement _part;
int _location;
public MovementChain(Movement part, int location)
{
_part = part;
_location = location;
}
public void setNext(Action next)
{
_next = next;
}
public void execute()
{
RepetitionRoutine(_part, _next, _location);
}
}
public void SetPlayerAnimation(int location, string endsprite, params Movement[] parts)
{
//Get the sprite object to be animated
if(parts.Count() == 0)
return;
TranslateTarget = "Sprite" + location.ToString();
OnPropertyChanged("TranslateTarget");
MovementChain first;
MovementChain last;
foreach(Movement part in parts)
{
MovementChain current = new MovementChain(part, location);
if(first == null)
{
first = current;
last = first;
}
else
{
last.setNext(current.execute);
last = current;
}
}
last.setNext(()=>SetPlayerSprite(location, endsprite));
first.execute();
}