[SOLVED] New to MonoGame, need help, error while trying to draw

Hello guys!
I’m new to MonoGame, and I’m trying to draw a prism with vertex and index buffer, while using a texture.
Right now I’m having this error, and I cant figure out what’s happening.

If someone could explain to me what’s happening, and how to solve it I would be very thankfull.

https://pastebin.com/T1RAdJPH -> Prism.cs

https://pastebin.com/U9yvtsyc -> Helper.cs

Thanks for you time!

Hey, welcome to the forum!

This error happens most commonly when the structure of the data does not map to the vertex input the shader expects. This seems to be the case here too. If you enable VertexColor on the basic effect, it expects color data in your vertex data. If you disable lighting iirc you don’t need normals. So in your case, you want to use VertexPositionColorTexture or even disable VertexColor as well and use VertexPositionTexture if you can manage with just a texture for the colors.

1 Like

Hi Jjagg, thanks for the help, the code now runs!

I’ve followed you advice and I’ve changed from VertexPositionNormalTexture to VertexPositionTexture.
The code runs but I can’t see my prism on the scene, am I doing something wrong?

I’m calling my prism class like this :

        protected override void Initialize()
        {
            System.IO.FileStream stream = new System.IO.FileStream(@"Content\Grass_double.jpg", System.IO.FileMode.Open);
            texture = Texture2D.FromStream(GraphicsDevice, stream);
            prism = new Prism(GraphicsDevice, 7, 2f, 1f, texture);            

            stream.Dispose();

            // TODO: Add your initialization logic here

            base.Initialize();
         }

         protected override void Draw(GameTime gameTime)
         {
             GraphicsDevice.Clear(Color.DarkViolet);
       
             prism.Draw(GraphicsDevice);

             base.Draw(gameTime);
          }

Right now I’m only seeing a Dark Violet screen.

Once again, thank you for you time helping me!

You should post the changes you made again to paste bin.

Double check your coordinates and world matrix. Or maybe you forgot to set the world matrix at all? Let me know if you need some help with that :slight_smile:

Here’s my new version of the class. https://pastebin.com/Mw3UC1pA - > prism v2

I’m already setting up my World matrix, I’m currently rechecking my coordinates, but I’m not finding what’s wrong.
I’ll keep you updated if I found the problem.

Once again thanks for your time guys

If it’s not error-ing anymore and you are drawing it but do not see it.

Then id say,

Turn off the culling i.e. set the cull mode to .none.
Check that you’re camera is not facing the wrong way i.e. either flip it the other way. Or just spin the camera position around the camera target leave that target to be location 0,0,0

I will say that i just gleemed it over the code isn’t to easy to understand.
it appears to be drawing a single top and bottom pointed prism there are all kinds of prism.

If this is just a example you are using to learn from on how to draw using a vertex and index buffer.
I think it would be easier to just straight write you a new example from scratch that works and is simpler.

I think I’m not creating the index buffer correctly, because the coordinates seem to be good.
I’m already creating the object near the origin point, and yes it’s a prism with symmetrical top and bottom layers(don’t really know how to call them). But I’ll try the culling mode to see if it helps.

This is an example to learn how to draw using index and vertex, because I’ll need to use it on an assignment where I’ll need to draw a map with these two techniques and using an height map.

Do you have any advice to improve the readability of the code? I’ve tried my best to keep it simple, but I’m always eager to learn how to improve things.

Well it’s not that it isn’t readable its that you’re basic algorithm itself is overly complicated.

Anyways you may continue with it if you like but since i was bored and had a few hours, i wrote you out a working example.

Note that i placed a old version of my camera class into it so you could visualize things better, it should work ok the newer one is a lot more complicated. I altered your algorithm quite a bit, so that it would basically one shot the vertex position and texture coordinates creation.
Now i only used a dot texture but the algorithm actually uses a pattern.
If you use one of you’re own load one in that is the shape of a diamond as the texture u v coordinates map to a diamond shaped texture.

Anyways i hope it helps to see someone else’s interpretation.

The cs file has the original 2 classes, It also has a additional couple camera classes i added, i will separate them into two posts…

using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace TiagocostasExamplePrj
{

    public class Game1 : Game
    {
        // hit f10 to change out of wireframe.
        // hit wasd or the arrow keys to look or move with the camera.
        // the camera will not care were you put it initially as it will look at the prism.

        GraphicsDeviceManager graphics;
        GraphicsDevice gd;
        SpriteBatch spriteBatch;
        Texture2D dot;

        /// <summary>
        /// The testing class
        /// </summary>
        Prism prismtest;

        /// <summary>
        /// well add a bool to turn on or off wireframe with f10
        /// </summary>
        public bool isWireFrame = true;

        // create a raster state for solid fill mode and ccw culling.
        RasterizerState rasterstate_Regular = new RasterizerState()
        {
            FillMode = FillMode.Solid,
            CullMode = CullMode.CullCounterClockwiseFace
        };
        // create a raster state for wireframe fill mode and no culling.
        RasterizerState rasterstate_Wire = new RasterizerState()
        {
            FillMode = FillMode.WireFrame,
            CullMode = CullMode.None
        };

        // camera and some constants
        public const float PI = (float)(Math.PI);
        public const float PI2 = (float)(Math.PI * 2.0d);
        public const float TODEGREES = 360.0f / PI2;
        public const float TORADIANS = PI2 / 360.0f;

        WorldSpaceObject obj_Prism = new WorldSpaceObject();
        WorldSpaceObject obj_Camera = new WorldSpaceObject();
        ViewSpaceCameraObjTransformer camTransformer = new ViewSpaceCameraObjTransformer();
        UserInputToOrientWorldObject objUiInput = new UserInputToOrientWorldObject();


        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            Window.AllowUserResizing = true;
            this.IsFixedTimeStep = true;
            this.TargetElapsedTime = TimeSpan.FromSeconds(1d / 60);
            this.IsMouseVisible = true;

        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            gd = GraphicsDevice;
            spriteBatch = new SpriteBatch(GraphicsDevice);
            dot = GetDotTexure(GraphicsDevice);
            prismtest = Prism.Load(GraphicsDevice, 10, 2, 1, dot);

            SetUpWorldObjects(0f);
        }

        #region couple loading helper methods

        public void SetUpWorldObjects(float yaxisDegreeDirection)
        {
            // well put the prism at -1 z
            obj_Prism.Position = new Vector3(0, 0, -1);
            obj_Prism.Forward = Vector3.Forward;

            // i was going to make the camera object rotate around the prism 
            // but i added this old version of my camera class instead.
            //Matrix temp = Matrix.CreateRotationY(TORADIANS * yaxisDegreeDirection);

            // well give the camera some distance but we dont care were it is really.
            obj_Camera.Position = new Vector3(-5, +2, 10);
            // well make it point towards the prism
            obj_Camera.Forward = Vector3.Normalize(obj_Prism.Position - obj_Camera.Position);
            // well set up the inital viewspace depending on the camera
            camTransformer.CreateCameraViewSpace(obj_Camera);
            // this is some extra stuff we might want to set
            objUiInput.SetWindowSizeRequiredForMouseLook(GraphicsDevice);
            objUiInput.SpeedRotational = .01f;
            objUiInput.SpeedMovement = .1f;
        }

        /// <summary>
        /// just create a dot texture instead of loading a texture.
        /// </summary>
        public Texture2D GetDotTexure(GraphicsDevice gd)
        {
            Texture2D tex = new Texture2D(gd, 1, 1);
            tex.SetData<Color>(new Color[1] { new Color((byte)255, (byte)255, (byte)255, (byte)255) });
            return tex;
        }

        #endregion

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// game-specific content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
                Exit();

            //
            // Well change if were working in wireframe or not should be timed but mehh.
            //
            if (Keyboard.GetState().IsKeyDown(Keys.F10))
            {
                if (isWireFrame)
                    isWireFrame = false;
                else
                    isWireFrame = true;
            }
            //
            // Any game object may act as the camera well use that class i added to have a camera.
            // Well move and look around with the key board keys wasd to roll zc or the arrows to move qe in out.
            // basically like any fps simulator type game.
            //
            // Lets update keypresses so that they apply to the camera object well pick to use.
            //
            // In this case its not a a actual visible world object its just are invisible object.
            // as the camera in to the world space.
            //
            obj_Camera = objUiInput.UpdateOrientation(obj_Camera);
            if (objUiInput.HasChangeOccured)
            {
                // if any changes are made we update the view matrix by using the camera world object
                camTransformer.CreateCameraViewSpace(obj_Camera);
            }

            base.Update(gameTime);
        }

        protected override void Draw(GameTime gameTime)
        {
            //
            // clear the backbuffer
            //
            gd.Clear(new Color(30,30,30,255));

            //
            // we use that bool f10 changes to set the rasterstate to the device we want
            //
            if (isWireFrame)
            {
                gd.RasterizerState = rasterstate_Wire;
            }
            else
            {
                gd.RasterizerState = rasterstate_Regular;
            }

            //
            // we draw the prism
            //
            prismtest.Draw(gd, obj_Prism.world, camTransformer.View, camTransformer.Projection, true);

            base.Draw(gameTime);
        }
    }

continued…

public class Prism
{
    #region Variables
    /// <summary>
    /// Number of prism faces
    /// </summary>
    private int prismSides;

    /// <summary>
    /// Height of the prism
    /// </summary>
    private float prismHeight;

    /// <summary>
    /// Diameter of the prism
    /// </summary>
    private float prismRadius;

    /// <summary>
    /// Placeholder for the texture on the sides
    /// </summary>
    private Texture2D prismSideTexture;

    /// <summary>
    /// prism BasicEffect
    /// </summary>
    public BasicEffect effect;

    /// <summary>
    /// The World Matrix somewhat redundant being here.
    /// Now if anything we should provide accessors to set the effect view and projection.
    /// </summary>
    private Matrix worldMatrix;
    #endregion

    // Requisite for draw user indexed primitives. 
    private VertexPositionTexture[] nverts;
    private short[] nIndexs;
    // Requisite for draw primitives.
    private VertexBuffer vertexBuffer;
    private IndexBuffer indexBuffer;

    /// <summary>
    /// Creates and initializes a prism class object at load time. 
    /// Returns it as desired by the users specifications.
    /// this method is static so that you call it like so... Prism p = Prism.Load(..) .
    /// </summary>
    public static Prism Load(GraphicsDevice device, int nSides, float height, float radius, Texture2D sideTexture)
    {
        var t = new Prism();
        t.prismSides = nSides;
        t.prismHeight = height;
        t.prismRadius = radius;
        t.prismSideTexture = sideTexture;
        if (nSides < 3)
            t.prismSides = 3;
        // you might want decimals and you can probably do this with a scaling matrix in your own vertex shader.
        if (height < 1f)
            t.prismHeight = 1f;
        if (radius < 1f)
            t.prismRadius = 1f;

        // __________________________________
        // moved this all to this load method
        //
        // All common stuff set up the effect initially.
        //
        t.effect = new BasicEffect(device);
        t.effect.LightingEnabled = false;
        t.effect.TextureEnabled = true;
        t.effect.Texture = t.prismSideTexture;

        // The game itself is really responsible for this not some arbitrary game object.
        if (t.worldMatrix == null) { t.worldMatrix = Matrix.Identity; }
        float aspectRatio = (float)device.Viewport.Width / device.Viewport.Height;
        t.effect.View = Matrix.CreateLookAt(new Vector3(0f, 4f, 0f), Vector3.Zero, Vector3.Up);
        t.effect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f), aspectRatio, 1.0f, 10.0f);

        //
        // build the prism
        //
        t.BuildPrism(device, t.prismSides, t.prismHeight, (int)(t.prismRadius));

        // i made this a static load to sort of be like blah forget the constructor.
        // so now its time to return the new prism object.
        return t;
    }

    /// <summary>
    /// Build the prism
    /// </summary>
    private void BuildPrism(GraphicsDevice gd, int sides, float height, float radius)
    {
        //
        // Get the vertices into a vertex array.
        // Note drawuserindexed primitives can use this.
        // However its not really using the vertex buffer this way.
        //
        nverts = GetPrismVertices(radius, height, sides);
        //
        // Send a vertex buffer to the device.
        // create the buffer, set the vertice array to that buffer, send the buffer to the device. 
        //
        vertexBuffer = new VertexBuffer(gd, VertexPositionTexture.VertexDeclaration, nverts.Length, BufferUsage.None);
        vertexBuffer.SetData(nverts);
        gd.SetVertexBuffer(vertexBuffer);

        //
        // set up the index buffer
        //
        nIndexs = new short[sides * 3 * 2];

        int offset = 0;
        // first set
        for (int i = 2; i < nverts.Length; i++)
        {

            int i0 = offset + 0;
            int i1 = offset + 1;
            int i2 = offset + 2;
            offset += 3;

            short v0 = (short)(0); // vertice [0] holds the up prism point.
            short v1 = (short)(i); // each side has 2 points other then top or bottom.
            short v2 = (short)(i + 1); // we know all our side points are from 2 to the end.
            //
            // now towards the end of this loop.
            // well wrap that second side vertice around back to vertice [2]
            //
            if (v2 >= nverts.Length)
            {
                v2 = 2;
            }
            // we can control our initial culling order.
            // i.e. the way vertices use backface or frontface culling right here.
            // So here ill set it to use counter clockwise winding (ccw)
            nIndexs[i0] = v0;
            nIndexs[i1] = v1;
            nIndexs[i2] = v2;
        }
        // second set
        for (int i = 2; i < nverts.Length; i++)
        {
            int i0 = offset + 0;
            int i1 = offset + 1;
            int i2 = offset + 2;
            offset += 3;

            short v0 = (short)(1); // vertice [1] holds the down prism point
            short v1 = (short)(i);
            short v2 = (short)(i + 1);
            if (v2 >= nverts.Length)
            {
                v2 = 2;
            }
            // reverse the input ordering to keep the winding counter clockwise
            nIndexs[i0] = v1;
            nIndexs[i1] = v2;
            nIndexs[i2] = v0;
        }

        indexBuffer = new IndexBuffer(gd, IndexElementSize.SixteenBits, offset + 1, BufferUsage.None);
        indexBuffer.SetData(nIndexs);
        gd.Indices = indexBuffer;
    }
    /// <summary>
    /// Returns all the vertices the first two indices are the top then bottom points.
    /// Followed by all the other vertices points.
    /// </summary>
    public VertexPositionTexture[] GetPrismVertices(float radius, float height, float nPositions)
    {
        VertexPositionTexture[] result = new VertexPositionTexture[(int)(nPositions) + 2];

        float degrees = 0;
        float radians = 0f;
        float x;
        float z;
        float textureU = .5f;
        float textureV = 0f;
        result[0] = new VertexPositionTexture(Vector3.Up * height, new Vector2(textureU, textureV));
        textureV = 1f;
        result[1] = new VertexPositionTexture(Vector3.Down * height, new Vector2(textureU, textureV));
        textureV = .5f;
        for (int i = 0; i < nPositions; i++)
        {
            degrees = i * (360 / nPositions);
            radians = (degrees * ((float)Math.PI / 180));
            float sin = (float)(Math.Sin(radians));
            float cos = (float)(Math.Cos(radians));
            x = radius * sin;
            z = radius * cos;
            textureU = (i) / (nPositions - 1);
            result[i + 2] = new VertexPositionTexture(new Vector3(x, 0f, z), new Vector2(textureU, textureV ));
        }
        return result;
    }

    public void Draw(GraphicsDevice device)
    {
        float aspectRatio = (float)device.Viewport.Width / device.Viewport.Height;
        effect.World = worldMatrix;
        effect.View = Matrix.CreateLookAt(new Vector3(0f, 0f, 1f), Vector3.Zero, Vector3.Up);
        effect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(65.0f), aspectRatio, .5f, 1000.0f);

        Draw(device, effect.World, effect.View, effect.Projection, true);
    }
    public void Draw(GraphicsDevice device, Matrix world, Matrix view, Matrix projection, bool useingUserIndexedPrims)
    {

        int triangleCount = nIndexs.Length / 3;

        //World Matrix
        effect.World = world;
        effect.View = view;
        effect.Projection = projection;

        effect.CurrentTechnique.Passes[0].Apply();

        if (useingUserIndexedPrims)
        {
            // With DrawUserIndexedPrimitives we can work with the arrays themselves by passing them each frame.
            device.DrawUserIndexedPrimitives(PrimitiveType.TriangleList, nverts, 0, nverts.Length, nIndexs, 0, triangleCount, VertexPositionTexture.VertexDeclaration);
        }
        else
        {
            // set buffers on device
            device.Indices = indexBuffer;
            device.SetVertexBuffer(vertexBuffer);

            // this way actually uses these buffers that we already set onto the device.
            device.DrawPrimitives(PrimitiveType.TriangleList, 0, triangleCount);
        }
    }

}


/// <summary>
/// simple camera class
/// Add one of these objects to your class.
/// </summary>
public class WorldSpaceObject
{
    public Matrix world = Matrix.Identity;

    /// <summary>
    /// This returns the orientation matrix without the translations.
    /// I.E this is the local rotations. 
    /// Typically ignored, it is here for convienience for a shaders.
    /// </summary>
    public Matrix LocalOrientationMatrix
    {
        get
        {
            Matrix m = Matrix.Identity;
            m.Forward = world.Forward;
            m.Right = world.Right;
            m.Up = world.Up;
            return m;
        }
    }

    /// <summary>
    /// While the rotations are in fact axis angle rotations. 
    /// About the current objects orientation, we still have a multiplication order.
    /// </summary>
    public bool UseYawPitchRollToRotate
    {
        get;
        set;
    }
    public Vector3 Position
    {
        get { return world.Translation; }
        set { world.Translation = value; }
    }
    public Vector3 Forward
    {
        get { return world.Forward; }
        set { world = Matrix.CreateWorld(world.Translation, value, world.Up); }
    }
    /// <summary>
    /// Move on a dimensional vector axis of the object itself. Note, we dont use the system vectors for this.
    /// </summary>
    public void Move(Vector3 moveSpeedInEachAxis)
    {
        var motion =
            moveSpeedInEachAxis.X * world.Right +
            moveSpeedInEachAxis.Y * world.Up +
            moveSpeedInEachAxis.Z * world.Forward
            ;
        Position += motion;
    }
    /// <summary>
    /// We designate the dimensional speed of rotation in dimension x y or z upon a perpendicular axis. 
    /// We may change the cw or ccw of rotation by using the reverse inverted axis vector. or just negating
    /// </summary>
    public void Rotate(Vector3 turnSpeedInDimension)
    {
        Vector3 temp = world.Translation;
        if (UseYawPitchRollToRotate)
        {
            world *=
                Matrix.CreateFromAxisAngle(world.Right, turnSpeedInDimension.Y) *
                Matrix.CreateFromAxisAngle(world.Up, turnSpeedInDimension.X) *
                Matrix.CreateFromAxisAngle(world.Forward, turnSpeedInDimension.Z)
                ;
            Forward = world.Forward;
        }
        else
        {
            world *=
                Matrix.CreateFromAxisAngle(world.Forward, turnSpeedInDimension.Z) *
                Matrix.CreateFromAxisAngle(world.Up, turnSpeedInDimension.X) *
                Matrix.CreateFromAxisAngle(world.Right, turnSpeedInDimension.Y)
                ;
            Forward = world.Forward;
        }
        world.Translation = temp;
    }
}


/// <summary>
/// This class takes a world space object to create a view camera. Via CreateCameraViewSpace.
/// You then get a combined world view projection matrix from GetWorldViewProjection.
/// </summary>
public class ViewSpaceCameraObjTransformer
{
    private Matrix projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, GraphicsDeviceManager.DefaultBackBufferWidth / GraphicsDeviceManager.DefaultBackBufferHeight, .5f, 1000);
    private Matrix viewSpace = Matrix.Identity;
    private Matrix combinedViewProjection;

    /// <summary>
    /// This can be used as a camera offset such as for a chase view.
    /// </summary>
    public Vector3 OffsetPosition
    {
        get;
        set;
    }
    /// <summary>
    /// Creates a camera view space, matrice and stores it.
    /// </summary>
    public void CreateCameraViewSpace(WorldSpaceObject worldObjectToUseAsCamera)
    {
        viewSpace = Matrix.CreateLookAt
            (
            worldObjectToUseAsCamera.Position + OffsetPosition,
            worldObjectToUseAsCamera.Forward + (worldObjectToUseAsCamera.Position + OffsetPosition),
            worldObjectToUseAsCamera.world.Up
            );
        combinedViewProjection = viewSpace * projection;
    }
    /// <summary>
    /// Takes a world space object matrice and transforms it. 
    /// By the view and projection matrixs into screen space.
    /// </summary>
    public Matrix GetWorldViewProjection(WorldSpaceObject worldObject)
    {
        return worldObject.world * combinedViewProjection;
    }
    /// <summary>
    /// Get a default projection matrix or set a new one
    /// </summary>
    public Matrix Projection
    {
        get
        {
            return projection;
        }
        set
        {
            projection = value;
            combinedViewProjection = viewSpace * projection;
        }
    }
    /// <summary>
    /// Get a view and projection matrix combined
    /// Note you normally use GetWorldViewProjection
    /// </summary>
    public Matrix ViewProjection
    {
        get
        {
            return combinedViewProjection;
        }
    }
    /// <summary>
    /// Get a view matrix alone
    /// Note you normally use GetWorldViewProjection
    /// </summary>
    public Matrix View
    {
        get
        {
            return viewSpace;
        }
    }
}

/// <summary>
/// Use keys mouse or what not To move WorldSpaceObjects Around.
/// This could probably be better.
/// </summary>
public class UserInputToOrientWorldObject
{
    Vector3 turnOnAxis = Vector3.Zero;
    Vector3 moveInAxis = Vector3.Zero;
    public float SpeedMovement = .01f;
    public float SpeedRotational = .01f;
    bool didAnyChangeOccur = false;
    public bool HasChangeOccured { get { return didAnyChangeOccur; } }
    Vector2 windowcenter = new Vector2(GraphicsDeviceManager.DefaultBackBufferWidth * .5f, GraphicsDeviceManager.DefaultBackBufferHeight * .5f);
    KeyboardState keyStates;
    MouseState mouseStates;

    public Keys KeyMoveRight = Keys.D;
    public Keys KeyMoveLeft = Keys.A;
    public Keys KeyMoveUp = Keys.W;
    public Keys KeyMoveDown = Keys.S;
    public Keys KeyMoveForward = Keys.E;
    public Keys KeyMoveBack = Keys.Q;

    public Keys KeyLookRight = Keys.Right;
    public Keys KeyLookLeft = Keys.Left;
    public Keys KeyLookUp = Keys.Up;
    public Keys KeyLookDown = Keys.Down;
    public Keys KeySpinCW = Keys.Z;
    public Keys KeySpinCCW = Keys.C;

    private bool useMouseLook = false;
    // if this is never called will just use the default key assignments
    public bool UseMouseLook
    {
        get { return useMouseLook; }
        set
        {
            if (value)
            {
                KeyMoveForward = Keys.W;
                KeyMoveBack = Keys.S;
                // just move them out of the way
                KeyMoveUp = Keys.Home;
                KeyMoveDown = Keys.PageUp;
            }
            else
            {
                KeyMoveRight = Keys.D;
                KeyMoveLeft = Keys.A;
                KeyMoveUp = Keys.W;
                KeyMoveDown = Keys.S;
                KeyMoveForward = Keys.E;
                KeyMoveBack = Keys.Q;
            }
            useMouseLook = value;
        }
    }

    public void SetWindowSizeRequiredForMouseLook(GraphicsDevice g)
    {
        windowcenter = new Vector2(g.Viewport.Width * .5f, g.Viewport.Height * .5f);
    }
    public void SetWindowSizeRequiredForMouseLook(int width, int height)
    {
        windowcenter = new Vector2(width * .5f, height * .5f);
    }

    public WorldSpaceObject UpdateOrientation(WorldSpaceObject worldObj)
    {
        didAnyChangeOccur = false;
        keyStates = Keyboard.GetState();
        mouseStates = Mouse.GetState();
        if (useMouseLook)
        {
            MouseLook();
            Move();
        }
        else
        {
            Rotate();
            Move();
        }
        if (didAnyChangeOccur)
        {
            worldObj.Move(moveInAxis);
            worldObj.Rotate(turnOnAxis);
        }
        return worldObj;
    }

    private void Rotate()
    {
        turnOnAxis = Vector3.Zero;
        if (keyStates.IsKeyDown(KeySpinCCW)) // roll ccw
        {
            turnOnAxis.Z = -SpeedRotational;
            didAnyChangeOccur = true;
        }
        if (keyStates.IsKeyDown(KeySpinCW)) // roll cw
        {
            turnOnAxis.Z = SpeedRotational;
            didAnyChangeOccur = true;
        }
        if (keyStates.IsKeyDown(KeyLookLeft)) // r ccw
        {
            turnOnAxis.X = SpeedRotational;
            didAnyChangeOccur = true;
        }
        if (keyStates.IsKeyDown(KeyLookRight)) // r cw
        {
            turnOnAxis.X = -SpeedRotational;
            didAnyChangeOccur = true;
        }
        if (keyStates.IsKeyDown(KeyLookUp)) // u cw
        {
            turnOnAxis.Y = SpeedRotational;
            didAnyChangeOccur = true;
        }
        if (keyStates.IsKeyDown(KeyLookDown)) // d ccw
        {
            turnOnAxis.Y = -SpeedRotational;
            didAnyChangeOccur = true;
        }
    }

    private void Move()
    {
        moveInAxis = Vector3.Zero;
        if (keyStates.IsKeyDown(KeyMoveForward)) // Forward
        {
            moveInAxis.Z = SpeedMovement;
            didAnyChangeOccur = true;
        }
        if (keyStates.IsKeyDown(KeyMoveBack)) // back
        {
            moveInAxis.Z = -SpeedMovement;
            didAnyChangeOccur = true;
        }
        if (keyStates.IsKeyDown(KeyMoveLeft)) // left
        {
            moveInAxis.X = -SpeedMovement;
            didAnyChangeOccur = true;
        }
        if (keyStates.IsKeyDown(KeyMoveRight)) // right
        {
            moveInAxis.X = SpeedMovement;
            didAnyChangeOccur = true;
        }
        if (keyStates.IsKeyDown(KeyMoveDown)) // down
        {
            moveInAxis.Y = -SpeedMovement;
            didAnyChangeOccur = true;
        }
        if (keyStates.IsKeyDown(KeyMoveUp)) // up
        {
            moveInAxis.Y = SpeedMovement;
            didAnyChangeOccur = true;
        }
    }

    private void MouseLook()
    {
        turnOnAxis = Vector3.Zero;
        Vector2 mousePos = new Vector2(mouseStates.Position.X, mouseStates.Position.Y) - windowcenter;
        Vector2 mouseAngle = Vector2.Normalize(mousePos);

        //if (mouseStates.LeftButton == ButtonState.Pressed)
        //{
        Matrix r = Matrix.Identity;
        mousePos.Normalize();

        if (mousePos.Y > 5f)
        {
            turnOnAxis.Y = SpeedRotational * mouseAngle.Y;
            didAnyChangeOccur = true;
        }
        if (mousePos.Y < 5f)
        {
            turnOnAxis.Y = SpeedRotational * mouseAngle.Y;
            didAnyChangeOccur = true;
        }
        if (mousePos.X > 5f)
        {
            turnOnAxis.X = SpeedRotational * mouseAngle.X;
            didAnyChangeOccur = true;
        }
        if (mousePos.X < 5f)
        {
            turnOnAxis.X = SpeedRotational * mouseAngle.X;
            didAnyChangeOccur = true;
        }
        
    }
}

} // ends the namespace

That definitely helped! Thanks a lot!
I’ve already started to work on my assignment thanks to your help!

I’m already drawing a map with an height map and applying textures.

Once again thanks for helping me through this!

Update

The problem was actually the camera was pointing at the wrong direction.

1 Like

Glad to help…