您的位置:首页 > 编程语言 > C#

C# Managed DirectX 三角形旋转(修改Direct 3D绘制流水线(渲染管线)中代码)

2015-01-27 22:53 549 查看
增加变量:

private float angle = 0.0f;
private float viewZ = -5.0f;


修改SetupMatrices方法:

private void SetupMatrices()
{
this.device.Transform.World = Matrix.RotationY(this.angle);
this.device.Transform.View = Matrix.LookAtLH(
new Vector3(0.0f, 3.0f, this.viewZ),
new Vector3(0.0f, 0.0f, 0.0f),
new Vector3(0.0f, 1.0f, 0.0f));
this.device.Transform.Projection = Matrix.PerspectiveFovLH(
(float) Math.PI / 4, 1.0f, 1.0f, 100.0f);
}


程序运行期间,device的两个变换参数要变,因此SetupMatrices方法放入渲染方法中

修改OnResetDevice方法:

public void OnResetDevice(object sender, EventArgs e)
{
/*
* Device参数变化时调用;
*/
Device dev = (Device) sender;
dev.RenderState.CullMode = Cull.None;
dev.RenderState.Lighting = false;
}


修改渲染方法:

public void Render()
{
if (this.device == null)
return;
if (this.pause) //当窗口最小化或者不是可视化时,停止渲染;
return;
this.device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.WhiteSmoke, 1.0f, 0);
this.SetupMatrices();
this.device.BeginScene();
/*
* 渲染代码必须放在这里;
*/
this.device.SetStreamSource(0, this.vertexBuffer, 0);
this.device.VertexFormat = CustomVertex.PositionColored.Format;
this.device.DrawPrimitives(PrimitiveType.TriangleList, 0, 1);
this.device.EndScene();
this.device.Present();
}


增加事件函数:

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Left:
this.angle += 0.1f;
break;
case Keys.Right:
this.angle -= 0.1f;
break;
case Keys.Down:
this.viewZ += 0.1f;
break;
case Keys.Up:
this.viewZ -= 0.1f;
break;
}
}


控制:

从键盘按下左右箭头键,使三角形分别以y轴为中心左右旋转;

从键盘按下上下箭头键,使三角形离观察者越来越远或者越来越近。

若要让三角形连续旋转,首先撤销KeyDown事件,然后修改SetupMatrices方法根据事件变化修改参数angle:

private void SetupMatrices()
{
int iTime = Environment.TickCount % 1000;
this.angle = iTime * (2.0f * (float) Math.PI) / 1000.0f;
this.device.Transform.World = Matrix.RotationY(this.angle);
this.device.Transform.View = Matrix.LookAtLH(
new Vector3(0.0f, 3.0f, this.viewZ),
new Vector3(0.0f, 0.0f, 0.0f),
new Vector3(0.0f, 1.0f, 0.0f));
this.device.Transform.Projection = Matrix.PerspectiveFovLH(
(float) Math.PI / 4, 1.0f, 1.0f, 100.0f);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐