WPF制作跟着鼠标跑的小球
界面代码:
<Window x:Class="MouseDetectBall.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:MouseDetectBall"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="500" Loaded="Window_Loaded">
<Grid Background="Blue">
<Canvas x:Name="canvas">
<Path Fill="White">
<Path.Data>
<EllipseGeometry x:Name="circle" RadiusX="10" RadiusY="10"/>
</Path.Data>
</Path>
</Canvas>
</Grid>
</Window>
后台代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Timers;
using System.Windows.Media.Animation;
namespace MouseDetectBall
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public const int TimeSet = 200;
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Timer thisTimer = new Timer(TimeSet);
thisTimer.Elapsed += UpdateMoveDirection;
thisTimer.Start();
}
private void UpdateMoveDirection(object sender, ElapsedEventArgs e)
{
Dispatcher.Invoke(new Action(() =>
{
// 获取鼠标所在点坐标
Point MouseLocation = Mouse.GetPosition(canvas);
// 把鼠标所在的位置点的坐标向量化
Vector mouseVector = Vector.Parse(MouseLocation.ToString());
// 获取圆圈现在的位置
Vector targetVector = Vector.Parse(circle.Center.ToString());
// 把两个向量的差单位化
Vector directionVect = mouseVector - targetVector;
directionVect.Normalize();
PointAnimation thisPointAnimation = new PointAnimation()
{
Duration = new Duration(TimeSpan.FromMilliseconds(TimeSet)),
By = new Point(directionVect.X * 10, directionVect.Y * 10),
};
circle.BeginAnimation(EllipseGeometry.CenterProperty, thisPointAnimation);
}));
}
}
}