前面我們已經完成了基本模型和自訂模型匯入,你會發現每次都通過代碼來添加一堆模型確實很麻煩,在Balder中可以使用Geometry做模型組,將各種各樣的模型添加到其中,這次我們簡單的一起來研究一下模型組,加上一個小小的動畫,如果這篇你看明白了,那麼就可以使用這個引擎開發出一個簡單的遊戲,期待你的成果。
最先我們還是從建立一個控制項開始,請建立一個控制項開啟其中的.cs檔案,增加代碼變成下面的樣子,
public Lesson04()
{
InitializeComponent();
//L1
Game game = new Game() { Width = 600, Height = 400 };
game.Camera = new Camera();
game.Camera.Position = new Coordinate(100, 120, 150);
game.Camera.Target = new Coordinate(0, 0, 0);
game.Children.Add(new OmniLight() { Position = new Coordinate(0, 0, 0) });
//L3
Game_Axis axis_x = new Game_Axis(new Vertex(-300, 0, 0), new Vertex(300, 0, 0), Colors.Red);
Game_Axis axis_y = new Game_Axis(new Vertex(0, -300, 0), new Vertex(0, 300, 0), Colors.Blue);
Game_Axis axis_z = new Game_Axis(new Vertex(0, 0, -300), new Vertex(0, 0, 300), Colors.Green);
//L4
Balder.Objects.Geometries.Geometry group = new Balder.Objects.Geometries.Geometry() { Name="MeshGroup" };
group.InteractionEnabled = true;
group.Children.Add(axis_x);
group.Children.Add(axis_y);
group.Children.Add(axis_z);
//L2
Mesh Teapot = new Mesh();
Teapot.Position = new Coordinate(0, 0, 0);
Teapot.AssetName = new Uri("/Balder_Studio;component/Res/teapot.ase", UriKind.Relative);
//L4
group.Children.Add(Teapot);
group.Children.Add(new Box() { Dimension = new Coordinate(10, 20, 30), Position = new Coordinate(100, 10, 0), Name = "MyBox" });
group.Children.Add(new Box() { Dimension = new Coordinate(10, 30, 10), Position = new Coordinate(10, 10, -100) });
game.Children.Add(group);
LayoutRoot.Children.Add(game);
}
好了,運行一下看看,你會見到一個茶壺,一個簡單的座標(座標軸這個類在Lesson03中請查看相關資訊),外加兩塊磚頭(Box)就如同文章開始的一樣,關於模型添加到group當中的那段代碼完全可以改造成下面的樣子,為了簡單理解,就不做太多的變化了。
public class MyGeometry : Balder.Objects.Geometries.Geometry
{
//you code
}
上面的內容主要是介紹如何編組,其實它和一個Children集合沒什麼區別,如果你理解Silverlight的容器機制,那麼就很容易搞明白。
下面來寫一個動畫,我們需要一個計時器來類比一個小型的迴圈,代碼如下:
DispatcherTimer _dispatchertimer = new DispatcherTimer();
_dispatchertimer.Tick += new EventHandler(_dispatchertimer_Tick);
_dispatchertimer.Interval = TimeSpan.FromMilliseconds(30);
如果你發現一些小錯誤,可能是需要using System.Windows.Threading,最後寫一段代碼在Lesson04類當中:
//模型組
Balder.Objects.Geometries.Geometry _meshgroup = null;
Balder.Objects.Geometries.Box _box = null;
//旋轉角度計數
float angle = 0;
float speed = 2;
void _dispatchertimer_Tick(object sender, EventArgs e)
{
if (_meshgroup == null)
_meshgroup = this.FindName("MeshGroup") as Balder.Objects.Geometries.Geometry;
if(_box==null)
_box = this.FindName("MyBox") as Balder.Objects.Geometries.Box;
_meshgroup.World = Balder.Math.Matrix.CreateRotationY(angle++);
_box.Position.Y += speed;
if (_box.Position.Y >= 50 || _box.Position.Y <= 0)
speed = -speed;
}
這段代碼中,angle的角度在不停的增加,建立Y軸的旋轉後的全局座標系矩陣賦值給模型組,達到整個模型組在旋轉目的,而Box則遵循一個Y軸上下移動的邏輯,這是最簡單的方式,相信理解起來並不困難:),關於FindName方法一般用的不是很頻繁,主要是為了避免前面和後面的代碼的閱讀誤解,使之有連貫性。
那麼最後我們運行一下看看效果吧:
如果你仍未看懂,可以下載代碼研究,3D方面的計算才剛剛開始,而下一步,我們說說攝像機和燈光:)
原始碼:點擊這裡下載工程
工程中如果缺少Balder.dll請在這裡快速下載:SL4_Balder.rar
推薦Silverlight遊戲開發部落格:深藍色右手