|
 | XNA 4.0 | |  |
| Poster | : mss1 | | Posts | : 40 | | Country | : USA | | City | : Somewhere, CT |
| | | | Posted by mss1 on 21/03/2011 at 18:49:08
| |
********************************
********************************
Disclaimer:
I'm learning XNA 4.0 as nice side hobby.
I posted my horrible horrible code, because
no one else seems to have done it...
and I wish someone had done it for me, since
the conversion is extremely painful for
someone just learning this stuff.
Notes:
1. Don't expect this to be clean code, its
the at the state the moment I got it to work
2. I was using XNA 4.0 and VS C# 2010
Hope this helps people just learning also!
********************************
******************************** | |
|
| | | | | | Poster | : mss1 | | Posts | : 40 | | Country | : USA | | City | : Somewhere, CT |
| | | | Posted by mss1 on 21/03/2011 at 18:50:09
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace TerrianTest
{
public struct VertexPositionNormalColored
{
public Vector3 Position;
public Color Color;
public Vector3 Normal;
public static int SizeInBytes = 7 * 4;
public readonly static VertexDeclaration VertexDeclaration = new VertexDeclaration
(
new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0),
new VertexElement(sizeof(float) * 3, VertexElementFormat.Color, VertexElementUsage.Color, 0),
new VertexElement(sizeof(float) * 3 + 4, VertexElementFormat.Vector3, VertexElementUsage.Normal, 0)
);
}
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
GraphicsDevice device;
int terrainWidth;
int terrainLength;
float[,] heightData;
VertexBuffer terrainVertexBuffer;
IndexBuffer terrainIndexBuffer;
VertexPositionNormalColored[] vertices;
int[] indices;
Effect effect;
Matrix viewMatrix;
Matrix projectionMatrix;
Vector3 cameraPosition = new Vector3(130, 30, -50);
float leftrightRot = MathHelper.PiOver2;
float updownRot = -MathHelper.Pi / 10.0f;
const float rotationSpeed = 0.02f;
const float moveSpeed = 30.0f;
MouseState originalMouseState;
Texture2D grassTexture;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
this.IsMouseVisible = true;
graphics.PreferredBackBufferWidth = 500;
graphics.PreferredBackBufferHeight = 500;
graphics.ApplyChanges();
Window.Title = "Riemer's XNA Tutorials -- Series 4";
base.Initialize();
}
protected override void LoadContent()
{
device = GraphicsDevice;
effect = Content.Load<Effect>("Series4Effects");
UpdateViewMatrix();
viewMatrix = Matrix.CreateLookAt(new Vector3(130, 30, -50), new Vector3(0, 0, -40), new Vector3(0, 1, 0));
projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, device.Viewport.AspectRatio, 0.3f, 1000.0f);
LoadVertices();
LoadTextures();
}
private void LoadVertices()
{
Texture2D heightMap = Content.Load<Texture2D>("heightmap"); LoadHeightData(heightMap);
VertexPositionNormalTexture[] terrainVertices = SetUpTerrainVertices();
int[] terrainIndices = SetUpTerrainIndices();
terrainVertices = CalculateNormals(terrainVertices, terrainIndices);
CopyToTerrainBuffers(terrainVertices, terrainIndices);
}
private void LoadTextures()
{
grassTexture = Content.Load<Texture2D>("grass");
}
private void LoadHeightData(Texture2D heightMap)
{
float minimumHeight = float.MaxValue;
float maximumHeight = float.MinValue;
terrainWidth = heightMap.Width;
terrainLength = heightMap.Height;
Color[] heightMapColors = new Color[terrainWidth * terrainLength];
heightMap.GetData(heightMapColors);
heightData = new float[terrainWidth, terrainLength];
for (int x = 0; x < terrainWidth; x++)
for (int y = 0; y < terrainLength; y++)
{
heightData[x, y] = heightMapColors[x + y * terrainWidth].R;
if (heightData[x, y] < minimumHeight) minimumHeight = heightData[x, y];
if (heightData[x, y] > maximumHeight) maximumHeight = heightData[x, y];
}
for (int x = 0; x < terrainWidth; x++)
for (int y = 0; y < terrainLength; y++)
heightData[x, y] = (heightData[x, y] - minimumHeight) / (maximumHeight - minimumHeight) * 30.0f;
}
private VertexPositionNormalTexture[] SetUpTerrainVertices()
{
VertexPositionNormalTexture[] terrainVertices = new VertexPositionNormalTexture[terrainWidth * terrainLength];
vertices = new VertexPositionNormalColored[terrainWidth * terrainLength];
for (int x = 0; x < terrainWidth; x++)
{
for (int y = 0; y < terrainLength; y++)
{
terrainVertices[x + y * terrainWidth].Position = new Vector3(x, heightData[x, y], -y);
terrainVertices[x + y * terrainWidth].TextureCoordinate.X = (float)x / 30.0f;
terrainVertices[x + y * terrainWidth].TextureCoordinate.Y = (float)y / 30.0f;
}
}
return terrainVertices;
}
private int[] SetUpTerrainIndices()
{
int counter = 0;
indices = new int[(terrainWidth - 1) * (terrainLength - 1) * 6];
for (int y = 0; y < terrainLength - 1; y++)
{
for (int x = 0; x < terrainWidth - 1; x++)
{
int lowerLeft = x + y * terrainWidth;
int lowerRight = (x + 1) + y * terrainWidth;
int topLeft = x + (y + 1) * terrainWidth;
int topRight = (x + 1) + (y + 1) * terrainWidth;
indices[counter++] = topLeft;
indices[counter++] = lowerRight;
indices[counter++] = lowerLeft;
indices[counter++] = topLeft;
indices[counter++] = topRight;
indices[counter++] = lowerRight;
}
}
return indices;
}
private VertexPositionNormalTexture[] CalculateNormals(VertexPositionNormalTexture[] vertices, int[] indices)
{
for (int i = 0; i < vertices.Length; i++)
vertices[i].Normal = new Vector3(0, 0, 0);
for (int i = 0; i < indices.Length / 3; i++)
{
int index1 = indices[i * 3];
int index2 = indices[i * 3 + 1];
int index3 = indices[i * 3 + 2];
Vector3 side1 = vertices[index1].Position - vertices[index3].Position;
Vector3 side2 = vertices[index1].Position - vertices[index2].Position;
Vector3 normal = Vector3.Cross(side1, side2);
vertices[index1].Normal += normal;
vertices[index2].Normal += normal;
vertices[index3].Normal += normal;
}
for (int i = 0; i < vertices.Length; i++)
vertices[i].Normal.Normalize();
return vertices;
}
private void CopyToTerrainBuffers(VertexPositionNormalTexture[] vertices, int[] indices)
{
//terrainVertexBuffer = new VertexBuffer(device, vertices.Length * VertexPositionNormalTexture.SizeInBytes, BufferUsage.WriteOnly);
//terrainVertexBuffer.SetData(vertices);
terrainVertexBuffer = new VertexBuffer(device, typeof(VertexPositionNormalTexture), vertices.Length, BufferUsage.WriteOnly);
terrainVertexBuffer.SetData(vertices.ToArray());
terrainIndexBuffer = new IndexBuffer(device, typeof(int), indices.Length, BufferUsage.WriteOnly);
terrainIndexBuffer.SetData(indices);
}
protected override void UnloadContent()
{
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
float timeDifference = (float)gameTime.ElapsedGameTime.TotalMilliseconds / 1000.0f;
ProcessInput(timeDifference);
base.Update(gameTime);
}
private void ProcessInput(float amount)
{
MouseState currentMouseState = Mouse.GetState();
if (currentMouseState != originalMouseState)
{
if (currentMouseState.RightButton == ButtonState.Pressed)
{
float xDifference = currentMouseState.X - originalMouseState.X;
float yDifference = currentMouseState.Y - originalMouseState.Y;
if (currentMouseState.X < device.Viewport.Width / 3) leftrightRot += rotationSpeed;
if (currentMouseState.X > device.Viewport.Width - device.Viewport.Width / 3) leftrightRot -= rotationSpeed;
if (currentMouseState.Y < device.Viewport.Height / 3) updownRot += rotationSpeed;
if (currentMouseState.Y > device.Viewport.Height - device.Viewport.Height / 3) updownRot -= rotationSpeed;
UpdateViewMatrix();
}
}
Vector3 moveVector = new Vector3(0, 0, 0);
KeyboardState keyState = Keyboard.GetState();
if (keyState.IsKeyDown(Keys.Up) || keyState.IsKeyDown(Keys.W))
moveVector += new Vector3(0, 0, -1);
if (keyState.IsKeyDown(Keys.Down) || keyState.IsKeyDown(Keys.S))
moveVector += new Vector3(0, 0, 1);
if (keyState.IsKeyDown(Keys.Right) || keyState.IsKeyDown(Keys.D))
moveVector += new Vector3(1, 0, 0);
if (keyState.IsKeyDown(Keys.Left) || keyState.IsKeyDown(Keys.A))
moveVector += new Vector3(-1, 0, 0);
if (keyState.IsKeyDown(Keys.Q))
moveVector += new Vector3(0, 1, 0);
if (keyState.IsKeyDown(Keys.Z))
moveVector += new Vector3(0, -1, 0);
AddToCameraPosition(moveVector * amount);
}
private void AddToCameraPosition(Vector3 vectorToAdd)
{
Matrix cameraRotation = Matrix.CreateRotationX(updownRot) * Matrix.CreateRotationY(leftrightRot);
Vector3 rotatedVector = Vector3.Transform(vectorToAdd, cameraRotation);
cameraPosition += moveSpeed * rotatedVector;
UpdateViewMatrix();
}
private void UpdateViewMatrix()
{
Matrix cameraRotation = Matrix.CreateRotationX(updownRot) * Matrix.CreateRotationY(leftrightRot);
Vector3 cameraOriginalTarget = new Vector3(0, 0, -1);
Vector3 cameraOriginalUpVector = new Vector3(0, 1, 0);
Vector3 cameraRotatedTarget = Vector3.Transform(cameraOriginalTarget, cameraRotation);
Vector3 cameraFinalTarget = cameraPosition + cameraRotatedTarget;
Vector3 cameraRotatedUpVector = Vector3.Transform(cameraOriginalUpVector, cameraRotation);
viewMatrix = Matrix.CreateLookAt(cameraPosition, cameraFinalTarget, cameraRotatedUpVector);
}
protected override void Draw(GameTime gameTime)
{
float time = (float)gameTime.TotalGameTime.TotalMilliseconds / 100.0f;
RasterizerState rs = new RasterizerState();
rs.CullMode = CullMode.None;
device.RasterizerState = rs;
device.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Black, 1.0f, 0);
DrawTerrain(viewMatrix);
base.Draw(gameTime);
}
private void DrawTerrain(Matrix currentViewMatrix)
{
effect.CurrentTechnique = effect.Techniques["Textured"];
effect.Parameters["xTexture"].SetValue(grassTexture);
Matrix worldMatrix = Matrix.Identity;
effect.Parameters["xWorld"].SetValue(worldMatrix);
effect.Parameters["xView"].SetValue(currentViewMatrix);
effect.Parameters["xProjection"].SetValue(projectionMatrix);
effect.Parameters["xEnableLighting"].SetValue(true);
effect.Parameters["xAmbient"].SetValue(0.4f);
effect.Parameters["xLightDirection"].SetValue(new Vector3(-0.5f, -1, -0.5f));
foreach (EffectPass pass in effect.CurrentTechnique.Passes)
{
pass.Apply();
device.Indices = terrainIndexBuffer;
device.SetVertexBuffer(terrainVertexBuffer);
device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, vertices.Length, 0, indices.Length / 3);
}
}
}
}
|
| |
|
| | | | | | Poster | : mss1 | | Posts | : 40 | | Country | : USA | | City | : Somewhere, CT |
| | | | Posted by mss1 on 21/03/2011 at 18:54:21
| |
Replace the Namespace with whatever your namespace is. | |
|
| | | | | | Poster | : mss1 | | Posts | : 40 | | Country | : USA | | City | : Somewhere, CT |
| | | | Posted by mss1 on 21/03/2011 at 19:00:56
| |
//----------------------------------------------------
//-- --
//-- www.riemers.net --
//-- Series 4: Advanced terrain --
//-- Shader code --
//-- --
//----------------------------------------------------
//------- Constants --------
float4x4 xView;
float4x4 xProjection;
float4x4 xWorld;
float3 xLightDirection;
float xAmbient;
bool xEnableLighting;
//------- Texture Samplers --------
Texture xTexture;
sampler TextureSampler = sampler_state { texture = <xTexture>; magfilter = LINEAR; minfilter = LINEAR; mipfilter=LINEAR; AddressU = mirror; AddressV = mirror;};
//------- Technique: Colored --------
struct ColVertexToPixel
{
float4 Position : POSITION;
float4 Color : COLOR0;
float LightingFactor: TEXCOORD0;
};
struct ColPixelToFrame
{
float4 Color : COLOR0;
};
ColVertexToPixel ColoredVS( float4 inPos : POSITION, float4 inColor: COLOR, float3 inNormal: NORMAL)
{
ColVertexToPixel Output = (ColVertexToPixel)0;
float4x4 preViewProjection = mul (xView, xProjection);
float4x4 preWorldViewProjection = mul (xWorld, preViewProjection);
Output.Position = mul(inPos, preWorldViewProjection);
Output.Color = inColor;
float3 Normal = normalize(mul(normalize(inNormal), xWorld));
Output.LightingFactor = 1;
if (xEnableLighting)
Output.LightingFactor = saturate(dot(Normal, -xLightDirection));
return Output;
}
ColPixelToFrame ColoredPS(ColVertexToPixel PSIn)
{
ColPixelToFrame Output = (ColPixelToFrame)0;
Output.Color = PSIn.Color;
Output.Color.rgb *= saturate(PSIn.LightingFactor) + xAmbient;
return Output;
}
technique Colored
{
pass Pass0
{
VertexShader = compile vs_2_0 ColoredVS();
PixelShader = compile ps_2_0 ColoredPS();
}
}
//------- Technique: Textured --------
struct TexVertexToPixel
{
float4 Position : POSITION;
float4 Color : COLOR0;
float LightingFactor: TEXCOORD0;
float2 TextureCoords: TEXCOORD1;
};
struct TexPixelToFrame
{
float4 Color : COLOR0;
};
TexVertexToPixel TexturedVS( float4 inPos : POSITION, float3 inNormal: NORMAL, float2 inTexCoords: TEXCOORD0)
{
TexVertexToPixel Output = (TexVertexToPixel)0;
float4x4 preViewProjection = mul (xView, xProjection);
float4x4 preWorldViewProjection = mul (xWorld, preViewProjection);
Output.Position = mul(inPos, preWorldViewProjection);
Output.TextureCoords = inTexCoords;
float3 Normal = normalize(mul(normalize(inNormal), xWorld));
Output.LightingFactor = 1;
if (xEnableLighting)
Output.LightingFactor = saturate(dot(Normal, -xLightDirection));
return Output;
}
TexPixelToFrame TexturedPS(TexVertexToPixel PSIn)
{
TexPixelToFrame Output = (TexPixelToFrame)0;
Output.Color = tex2D(TextureSampler, PSIn.TextureCoords);
Output.Color.rgb *= saturate(PSIn.LightingFactor) + xAmbient;
return Output;
}
technique Textured
{
pass Pass0
{
VertexShader = compile vs_2_0 TexturedVS();
PixelShader = compile ps_2_0 TexturedPS();
}
}
|
| |
|
| | | | | | Poster | : Anonymous | | Posts | : | | Country | : | | City | : |
| | | | Posted by Anonymous on 31/01/2013 at 14:53:14
| | // xna 4.0 reach profile changes will motill
// i also changed the camera behavior
// so right clicking lets loose of the mouse look
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace RemiersTutorial4
{
public class Pt2_camera : Microsoft.Xna.Framework.Game
{
public struct VertexPositionNormalColored
{
public Vector3 Position;
public Color Color;
public Vector3 Normal;
public static int SizeInBytes = 7 * 4;
public readonly static VertexDeclaration VertexDeclaration = new VertexDeclaration
(
new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0),
new VertexElement(sizeof(float) * 3, VertexElementFormat.Color, VertexElementUsage.Color, 0),
new VertexElement(sizeof(float) * 3 + 4, VertexElementFormat.Vector3, VertexElementUsage.Normal, 0)
);
}
GraphicsDeviceManager graphics;
public static GraphicsDevice device;
ushort terrainWidth; // high def can use int (needs better gpu basically dx10 capable)
ushort terrainLength;// reach profile cannot either short or ushort is to be used
float[,] heightData;
VertexBuffer terrainVertexBuffer;
IndexBuffer terrainIndexBuffer;
VertexDeclaration terrainVertexDeclaration;
VertexPositionNormalColored[] vertices;
ushort[] indices;
Effect effect;
Matrix viewMatrix;
Matrix projectionMatrix;
// camera code
Vector3 originalCameraPosition = new Vector3(130, 30, -50);
Vector3 cameraPosition = new Vector3(130, 30, -50);
float leftrightRot = MathHelper.PiOver2;
float updownRot = -MathHelper.Pi / 10.0f;
const float rotationSpeed = 0.3f;
const float moveSpeed = 30.0f;
MouseState originalMouseState;
bool cursorOn = false;
// ___________
public Pt2_camera()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
graphics.PreferredBackBufferWidth = 500;
graphics.PreferredBackBufferHeight = 500;
graphics.ApplyChanges();
Window.Title = "Riemer's XNA Tutorials -- Series 4";
Window.AllowUserResizing = true;
Window.ClientSizeChanged += new EventHandler<EventArgs>(OnUserResize);
base.Initialize();
}
public void OnUserResize(Object sender,EventArgs e)
{
// breakpoint here to see what hapens
//int dummybreakpointvar = 10;
}
protected override void LoadContent()
{
device = GraphicsDevice;
// camera stuff
UpdateViewMatrix();
Mouse.SetPosition(device.Viewport.Width / 2, device.Viewport.Height / 2);
originalMouseState = Mouse.GetState();
effect = Content.Load<Effect>("Series4Effects");
viewMatrix = Matrix.CreateLookAt(new Vector3(130, 30, -50), new Vector3(0, 0, -40), new Vector3(0, 1, 0));
projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, device.Viewport.AspectRatio, 0.3f, 1000.0f);
LoadVertices();
}
private void LoadVertices()
{
Texture2D heightMap = Content.Load<Texture2D>("heightmap"); LoadHeightData(heightMap);
SetUpTerrainVertices();
SetUpTerrainIndices();
CalculateNormals();
CopyToTerrainBuffers();
}
private void LoadHeightData(Texture2D heightMap)
{
float minimumHeight = float.MaxValue;
float maximumHeight = float.MinValue;
terrainWidth = (ushort)(heightMap.Width); // can use int ect when using hidef profile
terrainLength = (ushort)(heightMap.Height);
Color[] heightMapColors = new Color[terrainWidth * terrainLength];
heightMap.GetData(heightMapColors);
heightData = new float[terrainWidth, terrainLength];
for (int x = 0; x < terrainWidth; x++)
for (int y = 0; y < terrainLength; y++)
{
heightData[x, y] = heightMapColors[x + y * terrainWidth].R;
if (heightData[x, y] < minimumHeight) minimumHeight = heightData[x, y];
if (heightData[x, y] > maximumHeight) maximumHeight = heightData[x, y];
}
for (int x = 0; x < terrainWidth; x++)
for (int y = 0; y < terrainLength; y++)
heightData[x, y] = (heightData[x, y] - minimumHeight) / (maximumHeight - minimumHeight) * 30.0f;
}
private void SetUpTerrainVertices()
{
vertices = new VertexPositionNormalColored[terrainWidth * terrainLength];
for (int x = 0; x < terrainWidth; x++)
{
for (int y = 0; y < terrainLength; y++)
{
vertices[x + y * terrainWidth].Position = new Vector3(x, heightData[x, y], -y);
if (heightData[x, y] < 6)
vertices[x + y * terrainWidth].Color = Color.Blue;
else if (heightData[x, y] < 15)
vertices[x + y * terrainWidth].Color = Color.Green;
else if (heightData[x, y] < 25)
vertices[x + y * terrainWidth].Color = Color.Brown;
else
vertices[x + y * terrainWidth].Color = Color.White;
}
}
}
private void SetUpTerrainIndices()
{
indices = new ushort[(terrainWidth - 1) * (terrainLength - 1) * 6];
int counter = 0;
for (int y = 0; y < terrainLength - 1; y++)
{
for (int x = 0; x < terrainWidth - 1; x++)
{
ushort lowerLeft = (ushort)(x + y * terrainWidth);
ushort lowerRight = (ushort)((x + 1) + y * terrainWidth);
ushort topLeft = (ushort)(x + (y + 1) * terrainWidth);
ushort topRight = (ushort)((x + 1) + (y + 1) * terrainWidth);
indices[counter++] = topLeft;
indices[counter++] = lowerRight;
indices[counter++] = lowerLeft;
indices[counter++] = topLeft;
indices[counter++] = topRight;
indices[counter++] = lowerRight;
}
}
}
private void CalculateNormals()
{
for (int i = 0; i < vertices.Length; i++)
vertices[i].Normal = new Vector3(0, 0, 0);
for (int i = 0; i < indices.Length / 3; i++)
{
int index1 = indices[i * 3];
int index2 = indices[i * 3 + 1];
int index3 = indices[i * 3 + 2];
Vector3 side1 = vertices[index1].Position - vertices[index3].Position;
Vector3 side2 = vertices[index1].Position - vertices[index2].Position;
Vector3 normal = Vector3.Cross(side1, side2);
vertices[index1].Normal += normal;
vertices[index2].Normal += normal;
vertices[index3].Normal += normal;
}
for (int i = 0; i < vertices.Length; i++)
vertices[i].Normal.Normalize();
}
private void CopyToTerrainBuffers()
{
terrainVertexBuffer = new VertexBuffer(device, VertexPositionNormalColored.VertexDeclaration, vertices.Length,
BufferUsage.WriteOnly);
terrainVertexBuffer.SetData(vertices);
// hidef
//terrainIndexBuffer = new IndexBuffer(device, typeof(int), indices.Length, BufferUsage.WriteOnly);
// reach
terrainIndexBuffer = new IndexBuffer(device, typeof(ushort), indices.Length, BufferUsage.WriteOnly);
terrainIndexBuffer.SetData(indices);
}
protected override void UnloadContent()
{
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || KeyboardInput.isEscPressed())
this.Exit();
float timeDifference = (float)gameTime.ElapsedGameTime.TotalMilliseconds / 1000.0f;
if (Mouse.GetState().RightButton == ButtonState.Pressed)
{
if (cursorOn) { cursorOn = false; }
else { cursorOn = true; cameraPosition = originalCameraPosition; leftrightRot = 0f; updownRot = 0f; }
}
if (cursorOn)
{
ProcessUserInput(timeDifference);
}
else
{
}
KeyboardInput.Update();
base.Update(gameTime);
}
// camera control
private void ProcessUserInput(float amount)
{
MouseState currentMouseState = Mouse.GetState();
if (currentMouseState != originalMouseState)
{
float xDifference = currentMouseState.X - originalMouseState.X;
float yDifference = currentMouseState.Y - originalMouseState.Y;
leftrightRot -= rotationSpeed * xDifference * amount;
updownRot -= rotationSpeed * yDifference * amount;
Mouse.SetPosition(device.Viewport.Width / 2, device.Viewport.Height / 2);
UpdateViewMatrix();
}
Vector3 moveVector = new Vector3(0, 0, 0);
KeyboardState keyState = Keyboard.GetState();
if (keyState.IsKeyDown(Keys.Up) || keyState.IsKeyDown(Keys.W))
moveVector += new Vector3(0, 0, -1);
if (keyState.IsKeyDown(Keys.Down) || keyState.IsKeyDown(Keys.S))
moveVector += new Vector3(0, 0, 1);
if (keyState.IsKeyDown(Keys.Right) || keyState.IsKeyDown(Keys.D))
moveVector += new Vector3(1, 0, 0);
if (keyState.IsKeyDown(Keys.Left) || keyState.IsKeyDown(Keys.A))
moveVector += new Vector3(-1, 0, 0);
if (keyState.IsKeyDown(Keys.Q))
moveVector += new Vector3(0, 1, 0);
if (keyState.IsKeyDown(Keys.Z))
moveVector += new Vector3(0, -1, 0);
AddToCameraPosition(moveVector * amount);
}
//
private void AddToCameraPosition(Vector3 vectorToAdd)
{
Matrix cameraRotation = Matrix.CreateRotationX(updownRot) * Matrix.CreateRotationY(leftrightRot);
Vector3 rotatedVector = Vector3.Transform(vectorToAdd, cameraRotation);
cameraPosition += moveSpeed * rotatedVector;
UpdateViewMatrix();
}
private void UpdateViewMatrix()
{
Matrix cameraRotation = Matrix.CreateRotationX(updownRot) * Matrix.CreateRotationY(leftrightRot);
Vector3 cameraOriginalTarget = new Vector3(0, 0, -1);
Vector3 cameraOriginalUpVector = new Vector3(0, 1, 0);
Vector3 cameraRotatedTarget = Vector3.Transform(cameraOriginalTarget, cameraRotation);
Vector3 cameraFinalTarget = cameraPosition + cameraRotatedTarget;
Vector3 cameraRotatedUpVector = Vector3.Transform(cameraOriginalUpVector, cameraRotation);
viewMatrix = Matrix.CreateLookAt(cameraPosition, cameraFinalTarget, cameraRotatedUpVector);
}
protected override void Draw(GameTime gameTime)
{
float time = (float)gameTime.TotalGameTime.TotalMilliseconds / 100.0f;
RasterizerState rs = new RasterizerState();
rs.CullMode = CullMode.None;
device.RasterizerState = rs;
device.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Black, 1.0f, 0);
DrawTerrain(viewMatrix);
base.Draw(gameTime);
}
private void DrawTerrain(Matrix currentViewMatrix)
{
effect.CurrentTechnique = effect.Techniques["Colored"];
Matrix worldMatrix = Matrix.Identity;
effect.Parameters["xWorld"].SetValue(worldMatrix);
effect.Parameters["xView"].SetValue(currentViewMatrix);
effect.Parameters["xProjection"].SetValue(projectionMatrix);
effect.Parameters["xEnableLighting"].SetValue(true);
effect.Parameters["xAmbient"].SetValue(0.4f);
effect.Parameters["xLightDirection"].SetValue(new Vector3(-0.5f, -1, -0.5f));
foreach (EffectPass pass in effect.CurrentTechnique.Passes)
{
pass.Apply();
device.Indices = terrainIndexBuffer;
device.SetVertexBuffer(terrainVertexBuffer);
device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, vertices.Length, 0, indices.Length / 3);
}
}
}
} | |
|
|
 | | |  |
|
|
|
If you appreciate the amount of time I spend creating and updating these pages, feel free to donate -- any amount is welcome !
|
- Website design & DirectX code : Riemer Grootjans - ©2006 Riemer Grootjans
|
|