namespace WPFGameTutorial { public partial class Window3 : Window { Rectangle rect;
double speed = 5;
Point moveTo;
public Window3() {
InitializeComponent();
rect = new Rectangle();
rect.Fill = new SolidColorBrush(Colors.Red);
rect.Width = 50;
rect.Height = 50;
rect.RadiusX = 5;
rect.RadiusY = 5;
Carrier.Children.Add(rect);
Canvas.SetLeft(rect, 0);
Canvas.SetTop(rect, 0);//////////////////////////////////////////////////////////////////////////////////////////////////////////// DispatcherTimer dispatcherTimer = new DispatcherTimer(DispatcherPriority.Normal);
dispatcherTimer.Tick += new EventHandler(Timer_Tick);
dispatcherTimer.Interval = TimeSpan.FromMilliseconds(50);
dispatcherTimer.Start();
} private void Carrier_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) {
moveTo = e.GetPosition(Carrier);
} private void Timer_Tick(object sender, EventArgs e) {
double rect_X = Canvas.GetLeft(rect);
double rect_Y = Canvas.GetTop(rect);
Canvas.SetLeft(rect, rect_X + (rect_X < moveTo.X ? speed : -speed));
Canvas.SetTop(rect, rect_Y + (rect_Y < moveTo.Y ? speed : -speed));
}
}
}
double speed = 5;
Point moveTo;
public Window3() {
InitializeComponent();
rect = new Rectangle();
rect.Fill = new SolidColorBrush(Colors.Red);
rect.Width = 50;
rect.Height = 50;
rect.RadiusX = 5;
rect.RadiusY = 5;
Carrier.Children.Add(rect);
Canvas.SetLeft(rect, 0);
Canvas.SetTop(rect, 0);//////////////////////////////////////////////////////////////////////////////////////////////////////////// DispatcherTimer dispatcherTimer = new DispatcherTimer(DispatcherPriority.Normal);
dispatcherTimer.Tick += new EventHandler(Timer_Tick);
dispatcherTimer.Interval = TimeSpan.FromMilliseconds(50);
dispatcherTimer.Start();
} private void Carrier_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) {
moveTo = e.GetPosition(Carrier);
} private void Timer_Tick(object sender, EventArgs e) {
double rect_X = Canvas.GetLeft(rect);
double rect_Y = Canvas.GetTop(rect);
Canvas.SetLeft(rect, rect_X + (rect_X < moveTo.X ? speed : -speed));
Canvas.SetTop(rect, rect_Y + (rect_Y < moveTo.Y ? speed : -speed));
}
}
}
//优先级,有High,Normal等,當然優先級別越高,該實列對象擁有更要級別的執行權
DispatcherTimer dispatcherTimer = new DispatcherTimer(DispatcherPriority.Normal);
//調用時間處理程序 Timer_Tick 就是你下面寫的那個方法的名稱(這種寫法在C#中成為事件委託)
dispatcherTimer.Tick += new EventHandler(Timer_Tick);
//超過設定的時間間隔後調用一次Timer_Tick方法
dispatcherTimer.Interval = TimeSpan.FromMilliseconds(50);
//Go
dispatcherTimer.Start();
鼠标左键按下获得鼠标按下这一点坐标存入moveTo
dispatcherTimer.Interval = TimeSpan.FromMilliseconds(50);设定的时间执行一次Timer_Tick事件
Timer_Tick事件执行的操作:矩形给随鼠标左键按下的点移动
指定优先级
dispatcherTimer.Tick += new EventHandler(Timer_Tick);事件委托
dispatcherTimer.Interval = TimeSpan.FromMilliseconds(50); 指定时间间隔50秒
这句里面的DispatcherPriority.Normal 不加为什么也可以