C#+Direct3D9.0开发实例之月亮绕着地球转
http://tech.ddvip.com 2006年08月02日 社区交流
本文详细介绍C#+Direct3D9.0开发实例之月亮绕着地球转
现在改变主函数,调用我们写的初始化函数,并显示场景:
[STAThread]
static void Main()
{
using (Form1 EarthForm = new Form1())
{
EarthForm.InitializeGraphics();
EarthForm.Show();
while(EarthForm.Created)
{
EarthForm.Render();
Application.DoEvents();
}
EarthForm.Dispose();
}
运行程序,会显示一个空的窗体。
二、加入地球:
在这一步里需创建一个3D网格对象,来作为要显示的地球,为此,在工程中新加入一个类Earth,此类可以包含所创建的网格对象的信息。
加入一些相关变量,含义见注释:
public class Earth : BaseEarth
{
private Material[] mMaterials; //保存材质
private Texture[] mTextures; //保存纹理
private Matrix locationOffset; //用来保存网格对象的相对位置
private Mesh mMesh = null; //三角形网格对象
private Device meshDevice; //需要显示在哪个设备上。
}
在构造函数中,把Device设备拷贝到私有成员变量,这样就可以在这个类的其它方法内使用它,另外就是把位置变量进行赋值:
public Earth(ref Device device, Matrix location): base(ref device)
{
meshDevice = device;
locationOffset = location;
}
下面这个函数是装入.X文件。
public bool LoadMesh(string meshfile)
{
ExtendedMaterial[] mtrl;
try
{
// 装载文件
mMesh = Mesh.FromFile(meshfile, MeshFlags.Managed, meshDevice, out mtrl);
// 如果有材质的话,装入它们
if ((mtrl != null) && (mtrl.Length > 0))
{
mMaterials = new Material[mtrl.Length];
mTextures = new Texture[mtrl.Length];
// 得到材质和纹理
for (int i = 0; i < mtrl.Length; i++)
{
mMaterials[i] = mtrl[i].Material3D;
if ((mtrl[i].TextureFilename != null) && (mtrl[i].TextureFilename != string.Empty))
{
//前面得到的纹理的路径是相对路径,需要保存的是绝对路径,通过应用程序路径可以获得
mTextures[i] = TextureLoader.FromFile(meshDevice, @"..\..\" + mtrl[i].TextureFilename);
}
}
}
return true;
}
catch
{
return false;
}
}
作者:dandanCool 责编:豆豆技术应用