在前面的篇節中,基本上完成了一個Silverlight3D世界的構建,此時只需要一些邏輯和代碼就可以完成完整的遊戲,而今天我將最後一個部分補充:天空盒(SkyBox)。說到天空盒,以前學過D3D的朋友一定不陌生,其實就是六面方盒子,使用透視錯覺產生是一個球形。
從可以想想,由6張圖片可以組合封閉空間,所以先準備上面的這樣的一張圖,我直接從別的地方借來了6張標準的SkyBox圖片,關於SkyBox的圖片可以請3D美術師協助,或者藉助網路資源,另外,有一些專門製作天空盒的軟體。
最先需要準備圖片,把他們加入到工程中
我為了方便,這次不再構建很大的獨立控制項,而是通過繼承的方式直接獲得之前寫過的類:
public class Lesson09 : Lesson04
{
public Lesson09()
{
}
}
關於Lesson04,可以參見: Silverlight C# 遊戲開發:L4 模型組和簡單的動畫
我們將完成下面的這張的效果:
在繼承完了以後,需要對lesson04類做一些小小的改造,比如將Execution.Game給protected出來,將其中的DispatcherTimer的Tick事件執行方法virtual,這樣可以協助Lesson09少寫很多的代碼。
public class Lesson09 : Lesson04
{
public Lesson09()
{
//建立天空盒
Skybox skybox = new Skybox();
//天空盒6個方向的指定貼圖
skybox.Back = new ImageMap(Runtime.Instance.ContentManager.Load<Balder.Imaging.Image>("/Balder_Studio;component/SkyBox/cloudy_noon_BK.png"));
skybox.Bottom = new ImageMap(Runtime.Instance.ContentManager.Load<Balder.Imaging.Image>("/Balder_Studio;component/SkyBox/cloudy_noon_DN.png"));
skybox.Front = new ImageMap(Runtime.Instance.ContentManager.Load<Balder.Imaging.Image>("/Balder_Studio;component/SkyBox/cloudy_noon_FR.png"));
skybox.Left = new ImageMap(Runtime.Instance.ContentManager.Load<Balder.Imaging.Image>("/Balder_Studio;component/SkyBox/cloudy_noon_LF.png"));
skybox.Right = new ImageMap(Runtime.Instance.ContentManager.Load<Balder.Imaging.Image>("/Balder_Studio;component/SkyBox/cloudy_noon_RT.png"));
skybox.Top = new ImageMap(Runtime.Instance.ContentManager.Load<Balder.Imaging.Image>("/Balder_Studio;component/SkyBox/cloudy_noon_UP.png"));
//啟用天空盒,如果沒有啟用則不會顯示出來
skybox.IsEnabled = true;
//指定
game.Skybox = skybox;
}
double _sin = 0;
//重寫Lesson04中的Timer動畫
protected override void _dispatchertimer_Tick(object sender, EventArgs e)
{
//首先執行原來的
base._dispatchertimer_Tick(sender, e);
//判斷是否存在攝像機
if (game.Camera == null)
return;
//按照Sin曲線計算x,y,z的值,使之圍繞瀏覽Camera的TargetPoint
var x = System.Math.Cos(_sin) * 250;
var y = System.Math.Sin(2*_sin) * 250;
var z = System.Math.Sin(_sin) * 150;
game.Camera.Position.X = x;
game.Camera.Position.Y = y;
game.Camera.Position.Z = z;
//變化
_sin += 0.016;
}
}
上面的代碼就完成了天空盒的添加,如果你瞭解之前的內容,看起來很容易吧:)
點擊直接下載工程瀏覽和測試,運行效果如下:
工程中如果缺少Balder.dll請在這裡快速下載:SL4_Balder.rar
推薦Silverlight遊戲開發部落格:深藍色右手