WPF中使用Keydown事件怎么控制图片移动
使用WPF制作小游戏,按键盘方向键上和下控制一个图片的移动,需要按一次就到达指定位置,如何实现?如图:...
使用WPF制作小游戏,按键盘方向键上和下控制一个图片的移动,需要按一次就到达指定位置,如何实现?如图:
展开
展开全部
直接移动
Canvas.SetLeft
Canvas.SetTop
动画
<Canvas>
<Button Canvas.Left="50" Canvas.Top="50" Width="75" Height="25" Content="Ani" Click="button_Click"/>
</Canvas>
private void MoveTo(Control target, Point position)
{
var x = new DoubleAnimation();
var y = new DoubleAnimation();
x.To = position.X;
y.To = position.Y;
x.Duration = new Duration(TimeSpan.FromSeconds(1));
y.Duration = new Duration(TimeSpan.FromSeconds(1));
Storyboard.SetTarget(x, target);
Storyboard.SetTarget(y, target);
Storyboard.SetTargetProperty(x, new PropertyPath(Canvas.LeftProperty));
Storyboard.SetTargetProperty(y, new PropertyPath(Canvas.TopProperty));
var sb = new Storyboard();
sb.Children.Add(x);
sb.Children.Add(y);
sb.Completed += (obj, args) =>
{
MessageBox.Show("到位啦~!");
};
sb.Begin();
}
private void button_Click(object sender, RoutedEventArgs e)
{
this.MoveTo(sender as Button, new Point(100, 200));
}
Canvas.SetLeft
Canvas.SetTop
动画
<Canvas>
<Button Canvas.Left="50" Canvas.Top="50" Width="75" Height="25" Content="Ani" Click="button_Click"/>
</Canvas>
private void MoveTo(Control target, Point position)
{
var x = new DoubleAnimation();
var y = new DoubleAnimation();
x.To = position.X;
y.To = position.Y;
x.Duration = new Duration(TimeSpan.FromSeconds(1));
y.Duration = new Duration(TimeSpan.FromSeconds(1));
Storyboard.SetTarget(x, target);
Storyboard.SetTarget(y, target);
Storyboard.SetTargetProperty(x, new PropertyPath(Canvas.LeftProperty));
Storyboard.SetTargetProperty(y, new PropertyPath(Canvas.TopProperty));
var sb = new Storyboard();
sb.Children.Add(x);
sb.Children.Add(y);
sb.Completed += (obj, args) =>
{
MessageBox.Show("到位啦~!");
};
sb.Begin();
}
private void button_Click(object sender, RoutedEventArgs e)
{
this.MoveTo(sender as Button, new Point(100, 200));
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询