C # WPF Game notes a canvas instance DispatcherTimer
Rectangle rect; Create a block as a presentation object
Rect = new Rectangle ();
Rect. Fill = new SolidColorBrush (colors.red); Set the canvas's background setting
Rect. Width = 50;
Rect. Height = 50;
Rect. RadiusX = 5;
Rect. RadiusY = a 50*50 pixel fillet of the 5;//image 5*5 a red block object
CANVAS1. Children.add (rect);
Canvas.setleft (rect, 50);
Canvas.settop (rect, 50);
private void Form name _mouseleftbuttondown (object sender, MouseButtonEventArgs e)
{
}
Mouse click events
Point P = e.getposition (CANVAS1);
Storyboard Storyboard = new Storyboard ();//Create a motion animation
Creating an X-axis direction animation
DoubleAnimation doubleanimation = new DoubleAnimation (
Canvas.getleft (Rect),
P.x,//p.x is the X-coordinate p.y Y-coordinate
New Duration (Timespan.frommilliseconds (500))
);
Storyboard.settarget (DoubleAnimation, rect);
Storyboard.settargetproperty (DoubleAnimation, New PropertyPath ("(Canvas.Left)"));//When P. Y Canvas.Top as p.x canvas.left
Storyboard. Children.add (DoubleAnimation);
Dynamically loading animations into a resource
if (! Resources.contains ("Rectanimation")) {
Resources.add ("Rectanimation", Storyboard);
}
Animation playback
Storyboard. Begin ();
"C # WPF Game notes two canvas instance storyboard"
Double speed = 1; Set Move speed
Point MoveTo; Set a move target
Compositiontarget.rendering + = new EventHandler (Timer_tick); Thread
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));
}
First get the X, y position of the block, then let the block X, Y and moveto x, y to compare and judge whether it is +speed or-speed
C # WPF Game notes three-canvas instance CompositionTarget
Defining threads
DispatcherTimer DispatcherTimer = new DispatcherTimer (dispatcherpriority.normal);
Dispatchertimer.tick + = new EventHandler (Timer_tick);
Dispatchertimer.interval = Timespan.frommilliseconds (50); Repeat Interval
Dispatchertimer.start (); Start thread
The first sentence declares an interface timer DispatcherTimer, and sets its thread priority to normal, which is the standard setting that you can change according to your own needs, with a total of 10 levels.
The second sentence registers the Tick event, which is the event that is triggered by the timer interval.
The third sentence sets the interval for the Tick event, which can be in many ways, I use Timespan.frommilliseconds (), which is the interval in milliseconds.
The start thread for the four-sentence.
C # WPF Game notes Canvas instance