WPF制作跟着鼠标跑的小球

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


效果及参考视频

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值