Search This Blog

C# -----WPF / Silverlight Game (2) CompositionTarget

How to make the item move on the page? As I introduced before storyboard could be a nice
Solution, but here is another way to do that.

First step , same codes with before:
Run Visual studio 2008 sp1 edition
New project--->WPF Project.

On
Window2.xaml

Only put a Canvas here called Carrier

〈 Window x:Class="WPFGame.Window2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="WPFGame">
〈Canvas x:Name="Carrier" Width="800" Height="600" Background="Silver"
MouseLeftButtonDown="Carrier_MouseLeftButtonDown"/〉
〈/Window〉

cs file:
using System;

using System.
Collections.Generic;

using System.Linq;

using System.Text;

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.Shapes;

namespace WPFGame
{

public partial class Window2 : Window {

Rectangle rect;
double speed = 1;
Point moveTo;
public Window2() {
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);

CompositionTarget.Rendering += new EventHandler(Timer_Tick);
}

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

private void Carrier_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) {
moveTo = e.GetPosition(Carrier);
}
}
}
Then Ctrl+F5, done