Xna将在我运行游戏时崩溃-无错误

Xna将在我运行游戏时崩溃-无错误,xna,crash,Xna,Crash,我不知道发生了什么,所以这是我的代码。 我认为加载模型是一个问题,因为当我评论说它可行时。只是一个非常简单的网格上的第一人称相机,我试图放置一棵树 using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.X

我不知道发生了什么,所以这是我的代码。 我认为加载模型是一个问题,因为当我评论说它可行时。只是一个非常简单的网格上的第一人称相机,我试图放置一棵树

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
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 Series3D1
{
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        GraphicsDevice device;

        Effect effect;
        VertexPositionColor[] vertices;
        Matrix viewMatrix;
        Matrix projectionMatrix;
        int[] indices;

        float leftrightRot = MathHelper.PiOver2;
        float updownRot = -MathHelper.Pi / 10.0f;
        const float rotationSpeed = 0.3f;
        const float moveSpeed = 10.0f;

        // Set the position of the camera in world space, for our view matrix.
        Vector3 cameraPosition = new Vector3(50f,1.5f,-50f);
        Vector3 cameraLook;
        MouseState originalMouseState;
        SpriteFont font;
        Model tree1;

        private int terrainWidth = 100;
        private int terrainHeight = 100;
        private float[,] heightData;

        private bool flyMode = false;
        private bool JumpFlag = true;
        private int JumpCounter = 1;
        private float fallSpeed = -0.0f;
        private float jumpSpeed = 1.0f;
        private float movementSpeed = 1;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        protected override void Initialize()
        {
            graphics.PreferredBackBufferWidth = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width;
            graphics.PreferredBackBufferHeight = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height;
            graphics.IsFullScreen = true;
            graphics.ApplyChanges();
            Window.Title = "XNA";

            base.Initialize();
        }

        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);

            device = graphics.GraphicsDevice;

            effect = Content.Load<Effect>("effects"); SetUpCamera();

            Mouse.SetPosition(graphics.PreferredBackBufferWidth / 2, graphics.PreferredBackBufferHeight / 2);
            originalMouseState = Mouse.GetState();

            font = Content.Load<SpriteFont>("font");

            tree1 = LoadModel("AlanTree");

            PlayMusic();

            UpdateViewMatrix();

            LoadHeightData();
            SetUpVertices();
            SetUpIndices();
        }

        private void UpdateViewMatrix()
        {
            Matrix cameraRotation = Matrix.CreateRotationX(updownRot) * Matrix.CreateRotationY(leftrightRot);

            Vector3 cameraOriginalTarget = new Vector3(0, 0, -1);
            Vector3 cameraRotatedTarget = Vector3.Transform(cameraOriginalTarget, cameraRotation);
            Vector3 cameraFinalTarget = cameraPosition + cameraRotatedTarget;

            Vector3 cameraOriginalUpVector = new Vector3(0, 1, 0);
            Vector3 cameraRotatedUpVector = Vector3.Transform(cameraOriginalUpVector, cameraRotation);

            viewMatrix = Matrix.CreateLookAt(cameraPosition, cameraFinalTarget, cameraRotatedUpVector);
            cameraLook = cameraFinalTarget;
        }

        private void DrawText()
        {
            spriteBatch.Begin();
            spriteBatch.DrawString(font, "Game V1.0", new Vector2(20, 20), Color.White);
            spriteBatch.DrawString(font, "cameraLook: " + cameraLook, new Vector2(20, 40), Color.White);
            spriteBatch.DrawString(font, "cameraPostion: " + cameraPosition, new Vector2(20, 60), Color.White);
            spriteBatch.DrawString(font, "flyMode?: " + flyMode, new Vector2(20, 80), Color.White);
            spriteBatch.End();
        }

        private Model LoadModel(string assetName)
        {

            Model newModel = Content.Load<Model>(assetName); foreach (ModelMesh mesh in newModel.Meshes)
                foreach (ModelMeshPart meshPart in mesh.MeshParts)
                    meshPart.Effect = effect.Clone();
            return newModel;
        }

        protected override void UnloadContent()
        {
        }

        private void SetUpVertices()
        {
            vertices = new VertexPositionColor[terrainWidth * terrainHeight];
            for (int x = 0; x < terrainWidth; x++)
            {
                for (int y = 0; y < terrainHeight; y++)
                {
                    vertices[x + y * terrainWidth].Position = new Vector3(x, heightData[x, y], -y);
                    vertices[x + y * terrainWidth].Color = Color.White;
                }
            }
        }

        private void SetUpIndices()
        {
            indices = new int[(terrainWidth - 1) * (terrainHeight - 1) * 6];
            int counter = 0;
            for (int y = 0; y < terrainHeight - 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;
                }
            }
        }

        private void LoadHeightData()
        {
            heightData = new float[1000, 1000];
            float tempHolder = 0;

            for (int i = 0; i < 100; i++) {
                for (int j = 0; j < 100; j++) {
                    heightData[j, i] = tempHolder;
                }
            }
        }

        private void SetUpCamera()
        {
            viewMatrix = Matrix.CreateLookAt(new Vector3(0, 10, 0), new Vector3(0, 0, 0),     new Vector3(0, 0, -1));
            projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4,     device.Viewport.AspectRatio, 1.0f, 1000.0f);
        }

        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;

            MouseState currentMouseState = Mouse.GetState();
            if (currentMouseState != originalMouseState)
            {
                float xDifference = currentMouseState.X - originalMouseState.X;
                float yDifference = currentMouseState.Y - originalMouseState.Y;
                leftrightRot -= rotationSpeed * xDifference * timeDifference;
                updownRot -= rotationSpeed * yDifference * timeDifference;
                Mouse.SetPosition(graphics.PreferredBackBufferWidth / 2,     graphics.PreferredBackBufferHeight / 2);
                UpdateViewMatrix();
            }

            Vector3 moveVector = new Vector3(0, 0, 0);
            KeyboardState keyState = Keyboard.GetState();
            if (keyState.IsKeyDown(Keys.W))
                moveVector += new Vector3(0, 0, -movementSpeed);
            if (keyState.IsKeyDown(Keys.S))
                moveVector += new Vector3(0, 0, movementSpeed);
            if (keyState.IsKeyDown(Keys.D))
                moveVector += new Vector3(movementSpeed, 0, 0);
            if (keyState.IsKeyDown(Keys.A))
                moveVector += new Vector3(-movementSpeed, 0, 0);
            if (keyState.IsKeyDown(Keys.Enter))
            {
                if (flyMode == true)
                {
                    flyMode = false;
                }
                else if (flyMode == false)
                {
                    flyMode = true;
                }
                Thread.Sleep(100);
            }
            if (keyState.IsKeyDown(Keys.LeftControl))
                movementSpeed = 1.5f;
            else
                movementSpeed = 1.0f;
            if (flyMode)
            {
                if (keyState.IsKeyDown(Keys.Space))
                    moveVector += new Vector3(0, 1, 0);
                if (keyState.IsKeyDown(Keys.LeftShift))
                    moveVector += new Vector3(0, -1, 0);
            }
            else if (!flyMode) { 
                if (cameraPosition.Y > 1.5f) {
                    moveVector += new Vector3(0, fallSpeed, 0);
                    fallSpeed -= 0.1f;
                }
                else if (cameraPosition.Y < 1.5f)
                {
                    JumpCounter = 1;
                    fallSpeed = -0.0f;
                }
                if (JumpCounter == 10){

                }
                else if (keyState.IsKeyDown(Keys.Space) & JumpFlag == true){
                    moveVector += new Vector3(0, jumpSpeed, 0);
                    fallSpeed = -0.0f;
                    jumpSpeed += 0.001f;
                    JumpCounter += 1;
                }
            }
            AddToCameraPosition(moveVector * timeDifference);

            base.Update(gameTime);
        }

        private void PlayMusic()
        {
            Song song = Content.Load<Song>("Peaceful");
            MediaPlayer.Play(song);
        }

        private void AddToCameraPosition(Vector3 vectorToAdd)
        {
            Matrix cameraRotation = Matrix.CreateRotationY(leftrightRot);
            Vector3 rotatedVector = Vector3.Transform(vectorToAdd, cameraRotation);
            cameraPosition += moveSpeed * rotatedVector;
            UpdateViewMatrix();
        }

        protected override void Draw(GameTime gameTime)
        {
            device.Clear(Color.Black);

            RasterizerState rs = new RasterizerState();
            rs.CullMode = CullMode.None;
            rs.FillMode = FillMode.WireFrame;
            device.RasterizerState = rs;

            foreach (EffectPass pass in effect.CurrentTechnique.Passes)
            {
                pass.Apply();

                device.DrawUserIndexedPrimitives(PrimitiveType.TriangleList, vertices, 0,  vertices.Length, indices, 0, indices.Length / 3, VertexPositionColor.VertexDeclaration);
            }

            DrawText(); //puts the debug text to the screen
            DrawModel();

            base.Draw(gameTime);
        }

        private void DrawModel()
        {
            Matrix worldMatrix = Matrix.CreateScale(0.0005f, 0.0005f, 0.0005f) *     Matrix.CreateRotationY(MathHelper.Pi) * Matrix.CreateTranslation(new Vector3(19, 12, -5));

            Matrix[] treeTransforms = new Matrix[tree1.Bones.Count];
            tree1.CopyAbsoluteBoneTransformsTo(treeTransforms);
            foreach (ModelMesh mesh in tree1.Meshes)
            {
                foreach (Effect currentEffect in mesh.Effects)
                {
                    currentEffect.CurrentTechnique = currentEffect.Techniques["Colored"];
                    currentEffect.Parameters["xWorld"].SetValue(treeTransforms[mesh.ParentBone.Index] *     worldMatrix);
                    currentEffect.Parameters["xView"].SetValue(viewMatrix);
                    currentEffect.Parameters["xProjection"].SetValue(projectionMatrix);
                }
                mesh.Draw();
            }
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统线程;
使用Microsoft.Xna.Framework;
使用Microsoft.Xna.Framework.Audio;
使用Microsoft.Xna.Framework.Content;
使用Microsoft.Xna.Framework.GamerServices;
使用Microsoft.Xna.Framework.Graphics;
使用Microsoft.Xna.Framework.Input;
使用Microsoft.Xna.Framework.Media;
命名空间系列3D1
{
公共类游戏1:Microsoft.Xna.Framework.Game
{
图形管理器图形;
SpriteBatch SpriteBatch;
图形设备;
效应;
VertexPositionColor[]顶点;
矩阵视图矩阵;
矩阵投影矩阵;
int[]指数;
float leftrightRot=MathHelper.PiOver2;
float updownRot=-MathHelper.Pi/10.0f;
常数浮点旋转速度=0.3f;
恒浮子移动速度=10.0f;
//为视图矩阵设置摄影机在世界空间中的位置。
Vector3摄像机位置=新Vector3(50f,1.5f,-50f);
矢量3摄影机;
MouseState原住宅州;
SpriteFont字体;
模型树1;
私有内部地形宽度=100;
私人内部地形高度=100;
私有浮动[,]高度数据;
私有布尔飞行模式=假;
私有bool JumpFlag=true;
专用int跳线计数器=1;
私人浮动下降速度=-0.0f;
专用浮动跳线速度=1.0f;
专用浮动移动速度=1;
公共游戏1()
{
graphics=新的GraphicsDeviceManager(此);
Content.RootDirectory=“Content”;
}
受保护的覆盖无效初始化()
{
graphics.PreferredBackBufferWidth=GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width;
graphics.PreferredBackBufferHeight=GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height;
graphics.IsFullScreen=true;
graphics.ApplyChanges();
Window.Title=“XNA”;
base.Initialize();
}
受保护的覆盖void LoadContent()
{
spriteBatch=新spriteBatch(图形设备);
设备=graphics.GraphicsDevice;
效果=内容。加载(“效果”);设置摄影机();
Mouse.SetPosition(graphics.PreferredBackBufferWidth/2,graphics.PreferredBackBufferHeight/2);
originalMouseState=Mouse.GetState();
font=内容加载(“font”);
tree1=负荷模型(“AlanTree”);
播放音乐();
UpdateViewMatrix();
LoadHeightData();
设置顶点();
设置索引();
}
私有void UpdateViewMatrix()
{
矩阵摄影机旋转=矩阵.CreateRotationX(上下旋转)*矩阵.CreateRotationY(左右旋转);
Vector3 cameraOriginalTarget=新的Vector3(0,0,-1);
Vector3 cameraRotatedTarget=Vector3.Transform(cameraOriginalTarget,cameraRotation);
Vector3 cameraFinalTarget=cameraPosition+cameraRotatedTarget;
Vector3 cameraOriginalUpVector=新的Vector3(0,1,0);
Vector3 cameraRotatedUpVector=Vector3.Transform(cameraOriginalUpVector,cameraRotation);
viewMatrix=Matrix.CreateLookAt(cameraPosition、cameraFinalTarget、cameraRotatedUpVector);
cameraLook=cameraFinalTarget;
}
私有void DrawText()
{
spriteBatch.Begin();
spriteBatch.DrawString(字体,“游戏1.0版”,新矢量2(20,20),彩色,白色);
spriteBatch.DrawString(字体为“cameraLook:”+cameraLook,新矢量2(20,40),颜色为白色);
spriteBatch.DrawString(字体,“cameraPosition:”+cameraPosition,新矢量2(20,60),彩色.白色);
spriteBatch.DrawString(字体,“flyMode?”:“+flyMode,新矢量2(20,80),彩色.白色);
spriteBatch.End();
}
私有模型LoadModel(字符串assetName)
{
Model newModel=Content.Load(assetName);foreach(newModel.mesh中的ModelMesh网格)
foreach(ModelMeshPart meshPart中的meshPart.MeshParts)
meshPart.Effect=Effect.Clone();
返回新模型;
}
受保护的覆盖无效UnloadContent()
{
}
私有void SetUpVertices()
{
顶点=新顶点曝光颜色[地形宽度*地形高度];
对于(int x=0;x