3 Replies - 1745 Views - Last Post: 01 August 2013 - 02:39 PM

#1 Moonie878  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 31
  • Joined: 20-March 13

3D object pointing in the direction its facing

Posted 31 July 2013 - 05:08 PM

Hi I posted a similar problem i was having but i think i have the pointo function working now >>>

public void pointTowards(Vector3 point)
        {
            worldrot = Matrix.CreateLookAt(Position, point, Vector3.Up);
            worldrot = Matrix.Transpose(worldrot);
        }



but I cant figure out why its not working. The rest of my class code is

namespace _3d
{
    class Gameobject
    {

        public float Pitch { get; set; }
        public float Yaw { get; set; }
        public float Roll { get; set; }
        public float Scale { get; set; }
        public Model model { get; set; }

        public Vector3 Position { get; set; }

        public Matrix worldmat { get; protected set; }

       public Matrix worldrot = Matrix.Identity;
        
        public Gameobject(string filename = "", ContentManager content = null)
        {
            Pitch = 0f;
            Yaw = 0f;
            Roll = 0;
            Position.Normalize();
            Scale = 2;

            if (content != null)
            {
                model = content.Load<Model>(filename);
            }
        }

        public virtual void update(GameTime gametime)
        {

            worldrot = Matrix.CreateFromYawPitchRoll(Yaw, Pitch, Roll);
           
            Matrix scale = Matrix.CreateScale(Scale);
            Matrix trans = Matrix.CreateTranslation(Position);

            worldmat = scale * worldrot * trans;
          
        }



        public virtual void draw(Camera cam)
        {
            if (model != null)
            {
                foreach (ModelMesh mesh in model.Meshes)
                {
                    foreach (BasicEffect effect in mesh.Effects)
                    {
                        effect.EnableDefaultLighting();
                        effect.PreferPerPixelLighting = true;

                        effect.World = worldmat;
                        

                        effect.Projection = cam.projMat;

                        effect.View = cam.viewMat;

                        
                    }

                    mesh.Draw();
                }
            }
            
            
        }
public void pointTowards(Vector3 point)
        {
            worldrot = Matrix.CreateLookAt(Position, point, Vector3.Up);
            worldrot = Matrix.Transpose(worldrot);
        }
       

    }
}




and the way I am calling it is just pointTowards(objects position);

in a separate class which control's the states and movements.

Any help would be greatly appreciated

Is This A Good Question/Topic? 0
  • +

Replies To: 3D object pointing in the direction its facing

#2 Moonie878  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 31
  • Joined: 20-March 13

Re: 3D object pointing in the direction its facing

Posted 31 July 2013 - 05:35 PM

I'm sorry i was not very clear what im trying to do is get an object to face the way its moving

Sorry Again
Was This Post Helpful? 0
  • +
  • -

#3 BBeck  Icon User is offline

  • Here to help.
  • member icon


Reputation: 581
  • View blog
  • Posts: 1,292
  • Joined: 24-April 12

Re: 3D object pointing in the direction its facing

Posted 01 August 2013 - 05:59 AM

Start by going through my current tutorial on matrices.

http://virtuallyprog...s/Matrices.html

I'm currently in the process of writing a couple new tutorials that actually go into the internals of matrices. One of them might be particularly useful for you. It's not quite ready yet, but I'll see if I can't post some code or something later today.

Anyway, I don't see anywhere where you really define what direction it is facing. It will be facing the direction it was created in according to your current code.

I would probably think in terms of "getting the object to move in the direction that it is facing" rather than the other way around.

  Matrix ObjectsWorldMatrix;
  float AmountToMoveForward;
  Vector3 ForwardMovement;

  AmountToMoveForward = 0.01f;
  ForwardMovement = ObjectsWorldMatrix.Forward * AmountToMoveForward;
  ObjectsWorldMatrix *= Matrix.CreateTranslation(ForwardMovement);



So, that was an amount that I want the object to move forward by in each frame (probably 1/60th of a second depending on how fast the game is running - really you probably want to calculate the speed based on the frame rate which is variable even when it's fixed to 60 frames a second - it could be running slower).

Then I get the object's facing from it's world matrix (which should probably contain all the information necessary to place this object into the 3D world by itself). The "facing" is a vector. So, I can multiply that vector times the scaler (float) value of my speed and it will set the length of the facing vector to be my speed and pointing in the direction the object is facing.

NOTE: If the model is not created facing "forward", you may have to use another direction other than forward. Blender has a real bad habit of creating the models in the wrong facing. I'm still trying to work that one out.

Then I merely translate(move) the object's position held inside its matrix by the movement vector (arrow) I just created.

I'm skeptical that you can use Matrix.CreateLookAt() the way you are attempting to use it. The primary purpose of that method is to create a View matrix. I would be interested in knowing if that actually works, because I've never tried it. Maybe the transpose method fixes the issue between the world matrix and the view matrix. I would have thought it was Invert though. Not sure, like I said I've never attempted that.

This post has been edited by BBeck: 01 August 2013 - 06:09 AM

Was This Post Helpful? 0
  • +
  • -

#4 BBeck  Icon User is offline

  • Here to help.
  • member icon


Reputation: 581
  • View blog
  • Posts: 1,292
  • Joined: 24-April 12

Re: 3D object pointing in the direction its facing

Posted 01 August 2013 - 02:39 PM

Here is my Game1.cs code for my matrix tutorial. I'm doing basically everything with matrices as far as motion and positioning.

I used 3 models. The first is a green ground plane. The second is a yellow cube. And the third is a blue sphere.

I modeled everything in Blender and none of the models were textured. I used Vertex Paint mode to paint them.

The green ground plane is fixed in position. The camera is permenantly mounted to the Yellow Cube. I used two transformation matrices to position the camera. The first is basically a holding a position right above the center of the Yellow Cube. The camera always looks at this point. The second is the actual camera position which is relative to not only the Yellow Cube, but the camera mount position. I haphazardly added code to rotate this camera position transformation/world matrix. So, you can rotate the camera around the Yellow Cube. I could have further modified the camera position matrix to move it closer or further away from the camera mount position held in that matrix.

Maybe the camera thing is a little advanced. It doesn't necessarily have to be that complicated.

There is a second yellow cube called "the other yellow cube" that is controlled seperately from the one that the camera is attached to. The blue sphere orbits the OtherYellowCube constantly no matter where it goes.

So, the main purpose of this was to show how objects can be animated using just the object's world matrix. You can really see that with the OtherYellowCube. It's harder to see it with the cube that the camera is mounted to and with the camera orbiting that cube it makes it even harder to see.

I did it also to illustrate the fact that you have to move objects to the center of the game world (the origin at 0,0,0) in order to rotate them. And also using the blue sphere, how to modify this concept to cause one object to orbit another.

I plan on making this into a full blown tutorial, but I thought you might get some use out of just looking over the code.




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 MatrixTutorial
{
    public class Game1 : Microsoft.Xna.Framework.Game
    //==========================================================================================================
    //  MatrixTutorial
    //
    //  Purpose: To demonstrate matrices in use.
    //
    //  Notes:
    //      This code was written as an example on how matrices can be used to place objects into your 3D world. It
    //  focuses on maintianing all orientation, size, and position information inside the world matrix of the object.
    //  you certainly can maintain this information outside of the world matrix and then use it to build your world
    //  matrix at the last moment before it draws to the screen. But you can also, use the matrix to keep track of all
    //  the size, orientation, and position information of the object.
    //
    //      In addition to demonstrating how objects can be moved and positioned in the 3D world using only the object's
    //  world matrix, this demo shows how to do rotations using the object's world matrix. It demonstartes that you
    //  must move the object to the center of the 3D world in order to rotate it. You see this with all the Yellow Cube
    //  objects in the scene.
    //
    //      And the Blue Sphere object is included in the scene in order to take this one step further. The Blue Sphere 
    //  takes the rotation concept of moving to the origin (world's center) when rotating one step further. By moving by the
    //  offset of the Other Yellow Cube instead of it's own position/offset, it is made to orbit the Other Yellow Cube.
    //
    //      I took the time to deconstruct Matrix.CreateLookAt() that is so often used to create View matrices in XNA. I
    //  did this largely out of necessity to solve a problem I was having in another program. This provides an oppurtunity
    //  to take a look inside of CreateLookAt() and learn what happens inside that method and start to get an idea of why
    //  that it works the way that it does.
    //
    //      And finally, this demo has the camera setup to be permenantly attached to the Yellow Cube using transformation
    //  matrices. These transformation matrices position the camera relative to Yellow Cube. By rotating the camera position
    //  matrix it causes the camera to rotate around Yellow Cube. And at the same time, it is attached to Yellow Cube by the
    //  transformation matrices. So, to move the camera (other than it's rotation around Yellow Cube) you move Yellow Cube.
    //  Because the camera is attached to Yellow Cube, moving the cube moves the camera.
    //
    //      The ultimate purpose here is to give an example of matrices in action.
    //
    //==========================================================================================================
    {
        GraphicsDeviceManager graphics;
        Matrix ProjectionMatrix;    //Projection matrix to project the entire 3D scene onto the 2D backbuffer/screen.
        Matrix ViewMatrix;  //The "camera". Moves the 3D world to make it appear as if the "camera" is moving.
        Model GroundPlane;  //A fixed position green plane used to help show that motion is happening.
        Matrix GroundPlanesWorldMatrix; //The position and orientation of the ground plane, which never changes.
        Model YellowCube;   //The Yellow Cube model that the camera follows.
        Matrix YellowCubesWorldMatrix;  //Stores Yellow Cube's orientation, size, and position within our 3D world.
        Model BlueSphere;   //The Blue Sphere model that orbits the Other Yellow Cube.
        Matrix BlueSpheresWorldMatrix;  //Stores the Blue Sphere's orientation, size, and position within our 3D world.
        Model OtherYellowCube;  //The model for the Other Yellow Cube, which Blue Sphere orbits.
        Matrix OtherYellowCubesWorldMatrix; //The Other Yellow Cube's orientation, size, and position.
        Matrix CameraMountWorldMatrix;  //Stores a position above the Yellow Cube for the camera to "mount" to.
        Matrix CameraPositionWorldMatrix;   //Stores the position of the camera relative to the position of CameraMountWorldMatrix which is relative to YellowCubesWorldMatrix.


        const float CubeRotationSpeedInRadiansPerFrame = 0.05f; //Defines the rotational speed that the both cubes rotate at when the keyboard command tells them to rotate.


        public Game1()
        //==========================================================================================================
        //  Constructor
        //
        //  Purpose: To draw a given matrix on the screen at a given position.
        //
        //  Parameters:
        //
        //  Notes:
        //
        //==========================================================================================================
        {
            graphics = new GraphicsDeviceManager(this);
            graphics.PreferredBackBufferWidth = 1280;    //Screen width horizontal. Change this to fit your screen.
            graphics.PreferredBackBufferHeight = 720;    //Screen width vertical. Change this to fit your screen.
            graphics.IsFullScreen = false;  //Feel free to set this to true once your code works. 
            Content.RootDirectory = "Content";
        }
        //==========================================================================================================


        protected override void Initialize()
        //==========================================================================================================
        //  Initialize()
        //
        //  Purpose: Startup code that set the initial position of everything.
        //
        //  Parameters:
        //
        //  Notes:
        //      There are 3 models used here and YellowCube is used twice in two instances. All 4 objects are positioned 
        //  into the scene and then the camera is positioned 1.5 units above and 4 units behind the Yellow Cube's center.
        //  It's positioned relative to Yellow Cube's center because I made the center of the cube the center point in 
        //  Blender when I created it.
        //
        //==========================================================================================================
        {
            ProjectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, graphics.GraphicsDevice.Viewport.AspectRatio, 0.1f, 1000f);
            
            //Position the ground plane into the scene.
            GroundPlanesWorldMatrix = Matrix.Identity; //Initialize the ground's world matrix to empty.
            GroundPlanesWorldMatrix *= Matrix.CreateRotationX(-MathHelper.PiOver2);  //I did this because the model was created in Blender and Blender causes things to import sideways. With the ground that mattered.

            //Set the initial position of the other objects in the scene.
            YellowCubesWorldMatrix = Matrix.CreateTranslation(0f, 1f, 0f);  //Set initial position of Yellow Cube.
            OtherYellowCubesWorldMatrix = Matrix.CreateTranslation(4f, 1f, 10f);    //Set initial position of the Other Yellow Cube.
            BlueSpheresWorldMatrix = OtherYellowCubesWorldMatrix * Matrix.CreateTranslation(2f, 0f, 0f);    //Blue Sphere is attached to the Other Yellow Cube.

            CameraMountWorldMatrix = Matrix.CreateTranslation(0f, 1.5f, 0f);    //Position above Yellow Cube where the camera mounts.
            CameraPositionWorldMatrix = Matrix.CreateTranslation(0f, 0f, 4f);   //Camera is initially positioned here relative to the camera mount position.


            base.Initialize();
        }
        //==========================================================================================================


        protected override void LoadContent()
        //==========================================================================================================
        //  LoadContent()
        //
        //  Purpose: Load the model data into a Model object for all 4 models.
        //
        //  Parameters:
        //
        //  Notes:
        //      I created all 4 of these models in Blender. I used Vertex Painting mode (change from Object mode) to
        //  paint the objects the color they have. These are very simple models and have no texture in them.
        //
        //==========================================================================================================
        {
            GroundPlane = Content.Load<Model>("Plane");
            YellowCube = Content.Load<Model>("YellowCube");
            OtherYellowCube = Content.Load<Model>("YellowCube");
            BlueSphere = Content.Load<Model>("BlueSphere");
        }
        //==========================================================================================================


        protected override void UnloadContent()
        //==========================================================================================================
        //  UnloadContent()
        //
        //  Purpose: Not Used here.
        //
        //  Parameters:
        //
        //  Notes:
        //
        //==========================================================================================================
        {
            
        }
        //==========================================================================================================


        private Matrix LookAt(Vector3 Eye, Vector3 Target, Vector3 up)
        //==========================================================================================================
        //  LookAt()
        //
        //  Purpose: To simulate Matrix.CreateLookAt().
        //
        //  Parameters:
        //      Eye - This sets where the camera is postioned.
        //      Target - This defines a point that the camera looks toward.
        //      up - This orients the camera by defining which direction is above the Eye position.
        //
        //  Notes:
        //      Writing this function (and I mostly modified code I found on the Internet) really taught me what is
        //  going on inside the LookAt method. You can't take apart the actual CreateLookAt method of the Matrix
        //  class, but this is the next best thing.
        //
        //      I verified that it takes the exact same input and produces the exact same output as the CreateLookAt
        //  method for XNA's Matrix class. You can use it interchangably with that method and I've commented out code
        //  in this example to allow you to easily switch between the two to see what I mean. Studying this code
        //  will help you understand what happens when a View matrix is defined.
        //
        //      What this method does is create a 3D X,Y,Z axis. This axis can be rotated/oriented in any direction
        //  compared to the 3D world. The axis can also be positioned anywhere in the 3D world. This "axis" is 
        //  defined by creating three 3D vectors. The vectors are mutually perpendicular. That means that all of them
        //  are 90 degrees away from one another. Or more plainly, the 3 form their own X,Y,Z axis using 3 vectors.
        //  Think of the three vectors as being arrows with their tails all at the world's origin (0,0,0) and all
        //  3 vectors/arrows have their head at the point defined. The "Eye" position is used to position this axis
        //  anywhere in the 3D world.
        //
        //      You'll notice that the Orientation matrix has 3 axes, an X,Y, and Z axis. These 3 axes define an
        //  orientation or rotation. By rotating these 3 axes, you rotate the orientation information in this matrix.
        //  Each axis is a vector/arrow or 1 unit in length. As a vector, it has and X,Y, and Z coordinate to define
        //  the "arrow head", or position, of the vector. These vectors should always have a length of one, which means
        //  that they are "normalized". And they should always stay mutually perpendicular to one another (90 degrees
        //  apart from one another).
        //
        //      To build the orientation matrix, you have to create the three axes. The zAxis is the most straight
        //  forward. Using vector subtraction, we get a vector that points from the Eye position to the Target postion.
        //  This is almost certainly not a vector with a length of one. So, you have to normalize the vector to 
        //  change its length to one while keeping it pointing in the exact same direction. Next, we need a vector
        //  that points 90 degrees to the right of this Z axis to form an X axis.
        //
        //      This is where the "Up" parameter gets used. Up is a second vector that points "above" the "camera"
        //  that we are defining here. It points "above" the Z axis we just created. So, if the "camera" is upside
        //  down then "above" points down. "Above" could be any possible direction depending on how this camera/matrix
        //  is oriented. By using "Up" we are telling this method where we want "Up", or above, to be.
        //
        //      The vector cross product is a mathematical function that produces a third vector. The two input vectors
        //  define a plane. The two vectors can exist on one plane and one plane only (you cannot draw any other plane
        //  that had both vectors on that plane). Think of the two vectors as arrows forming a V. The two of them
        //  together define a plane that is not necessarily parallel to any axis. The vector cross product produces a
        //  third vector that points DIRECTLY out of that plane. It is 90 degrees from the plane. In otherwords, in
        //  points perfectly out of the plane. In this case, our plane is the vertical plane of our Z axis. So, a
        //  vector pointing out of it will point perfectly to the right, 90 degrees from or, of the Z axis. In other
        //  words, it forms our X axis. 
        //  
        //      If we likewise take the cross product of our newly created Z and X axis, they form a plane between them
        //  and the resulting vector will be a new vector that points mutually perpendicular out of that plane. In
        //  other words, we just created our Y axis. And now we have a full 3D axis defined with a different orientation
        //  from our 3D world. So, this axis stores an orientation (or rotation).
        //
        //      I believe the Y axis does not require normalization because the two axes that it was formed out of were
        //  normalized and so the result is normalized. Failing to normalize the xAxis gives a different result than the
        //  CreateLookAt() method of the Matrix class.
        //  
        //      The Eye value is used to position this axis within the 3D world. So, the resulting matrix stores an
        //  orientation and a position at the same time.
        //
        //==========================================================================================================
        {
            Vector3 zAxis = Eye - Target;    // The "look-at" vector.
            zAxis.Normalize();  //Change its length to be one unit long.
            Vector3 xAxis = Vector3.Cross(up, zAxis);// The "right" vector.
            xAxis.Normalize();  //Change its length to be one unit long.
            Vector3 yAxis = Vector3.Cross(zAxis, xAxis);     // The "up" vector.
            // Create a 4x4 orientation matrix from the right, up, and at vectors
            Matrix Orientation = new Matrix(
                   xAxis.X, yAxis.X, zAxis.X, 0,
                   xAxis.Y, yAxis.Y, zAxis.Y, 0,
                   xAxis.Z, yAxis.Z, zAxis.Z, 0,
                      0,       0,       0,     1
                   );
            // Create a 4x4 translation matrix by negating the Eye position.
            Matrix Translation = new Matrix(
                     1,      0,      0,     0,
                     0,      1,      0,     0, 
                     0,      0,      1,     0,
                   -Eye.X, -Eye.Y, -Eye.Z,  1
                  );
            // Combine the Orientation and Translation to produce the output result as a matrix.
            return (Translation * Orientation);
        }
        //==========================================================================================================


        protected override void Update(GameTime gameTime)
        //==========================================================================================================
        //  Update()
        //
        //  Purpose: Make changes every frame to handle keyboard input and move the models.
        //
        //  Parameters:
        //      gameTime - Standard XNA.
        //
        //  Notes:
        //      The first thing this section does is save the positions of the YellowCube and the OtherYellowCube because
        //  this information is used to rotate these cubes as well as to do the orbit with Blue Sphere.
        //
        //      Then it processes all Keyboard input. I've pretty much setup every possible rotation of the two yellow
        //  cubes as keyboard keys. I've also setup forward and backwards motion. And the rotation of the camera to
        //  orbit the Yellow Cube is setup on the keyboard as well. I've kept this codes as straight forward as possible
        //  to make it easy to see how it works.
        //
        //      After this, Blue Sphere is made to orbit the OtherYellowCube. The movement key also causes Blue Sphere to
        //  move whenever the OtherYellowCube moves. So, it stays right with the OtherYellowCube regardless of where it goes.
        //
        //      The transformation matrices are then used to define the position where the camera is at relative to the
        //  YellowCube. Since this is relative, any movement of the Yellow Cube will cause the camera to go with it.
        //
        //      And finally the View matrix (camera) is defined. I've created 3 differnt ways to define the location of the
        //  camera relative to the YellowCube. The first is the standard way using the matrices. The third is the exact
        //  same thing using my custom LookAt() method instead of the one built into the Matrix class so that you can see
        //  that they truely do the same thing. The second one is the same thing using vectors instead of matrices for
        //  whatever that's worth. It at least shows that this is not the only way to do this. The vector example is not
        //  setup to allow rotation/orbiting the camera.
        //
        //==========================================================================================================
        {
            KeyboardState KBState;
            Vector3 YellowCubesPosition;
            Vector3 OtherYellowCubesPosition;
            Matrix Camera;
            Matrix CameraMount;


            //Current positions must be saved so that we can move the models back after rotating them.
            YellowCubesPosition = YellowCubesWorldMatrix.Translation;
            OtherYellowCubesPosition = OtherYellowCubesWorldMatrix.Translation;

            KBState = Keyboard.GetState();
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();
            if (KBState.IsKeyDown(Keys.Escape)) this.Exit();


            if (KBState.IsKeyDown(Keys.C)) CameraPositionWorldMatrix *= Matrix.CreateRotationY(CubeRotationSpeedInRadiansPerFrame);
            if (KBState.IsKeyDown(Keys.Z)) CameraPositionWorldMatrix *= Matrix.CreateRotationY(-CubeRotationSpeedInRadiansPerFrame);

            //Yellow Cube Controls. (Controls the camera only because the camera is attached to the Yellow Cube.)
            if (KBState.IsKeyDown(Keys.W)) YellowCubesWorldMatrix *= Matrix.CreateTranslation(YellowCubesWorldMatrix.Forward * 0.1f);
            if (KBState.IsKeyDown(Keys.S)) YellowCubesWorldMatrix *= Matrix.CreateTranslation(YellowCubesWorldMatrix.Forward * -0.1f);
            if (KBState.IsKeyDown(Keys.D))
            {
                YellowCubesWorldMatrix *= Matrix.CreateTranslation(-YellowCubesPosition);   //Move to the center of the universe.
                YellowCubesWorldMatrix *= Matrix.CreateRotationY(-CubeRotationSpeedInRadiansPerFrame);  //Rotates on the "local" Y axis
                YellowCubesWorldMatrix *= Matrix.CreateTranslation(YellowCubesPosition);    //Move back.
            }
            if (KBState.IsKeyDown(Keys.A))
            {
                YellowCubesWorldMatrix *= Matrix.CreateTranslation(-YellowCubesPosition);
                YellowCubesWorldMatrix *= Matrix.CreateRotationY(CubeRotationSpeedInRadiansPerFrame);  //Rotates on the "local" Y axis
                YellowCubesWorldMatrix *= Matrix.CreateTranslation(YellowCubesPosition);
            }
            if (KBState.IsKeyDown(Keys.E))
            {
                YellowCubesWorldMatrix *= Matrix.CreateTranslation(-YellowCubesPosition);
                YellowCubesWorldMatrix *= Matrix.CreateRotationX(CubeRotationSpeedInRadiansPerFrame);  //Rotates on the "local" X axis
                YellowCubesWorldMatrix *= Matrix.CreateTranslation(YellowCubesPosition);
            }
            if (KBState.IsKeyDown(Keys.Q))
            {
                YellowCubesWorldMatrix *= Matrix.CreateTranslation(-YellowCubesPosition);
                YellowCubesWorldMatrix *= Matrix.CreateRotationX(-CubeRotationSpeedInRadiansPerFrame);  //Rotates on the "local" X axis
                YellowCubesWorldMatrix *= Matrix.CreateTranslation(YellowCubesPosition);
            }
            if (KBState.IsKeyDown(Keys.D3))
            {
                YellowCubesWorldMatrix *= Matrix.CreateTranslation(-YellowCubesPosition);
                YellowCubesWorldMatrix *= Matrix.CreateRotationZ(CubeRotationSpeedInRadiansPerFrame);  //Rotates on the "local" Z axis
                YellowCubesWorldMatrix *= Matrix.CreateTranslation(YellowCubesPosition);
            }
            if (KBState.IsKeyDown(Keys.D1))
            {
                YellowCubesWorldMatrix *= Matrix.CreateTranslation(-YellowCubesPosition);
                YellowCubesWorldMatrix *= Matrix.CreateRotationZ(-CubeRotationSpeedInRadiansPerFrame);  //Rotates on the "local" Z axis
                YellowCubesWorldMatrix *= Matrix.CreateTranslation(YellowCubesPosition);
            }


            //Keyboard control for the "other" yellow cube. (The one the camera is not attached to.)
            if (KBState.IsKeyDown(Keys.O))
            {
                OtherYellowCubesWorldMatrix *= Matrix.CreateTranslation(OtherYellowCubesWorldMatrix.Forward * 0.1f);    //Move the Other Yellow Cube forward.
                BlueSpheresWorldMatrix *= Matrix.CreateTranslation(OtherYellowCubesWorldMatrix.Forward * 0.1f);     //Blue Sphere is attached to the Other Yellow Cube.
            }
            if (KBState.IsKeyDown(Keys.L))
            {
                OtherYellowCubesWorldMatrix *= Matrix.CreateTranslation(OtherYellowCubesWorldMatrix.Forward * -0.1f);   //Negative causes it to move backwards.
                BlueSpheresWorldMatrix *= Matrix.CreateTranslation(OtherYellowCubesWorldMatrix.Forward * -0.1f);    //Blue Sphere is attached to the Other Yellow Cube.
            }
            if (KBState.IsKeyDown(Keys.OemSemicolon))
            {
                OtherYellowCubesWorldMatrix *= Matrix.CreateTranslation(-OtherYellowCubesPosition);   //Move to the center of the universe.
                OtherYellowCubesWorldMatrix *= Matrix.CreateRotationY(-CubeRotationSpeedInRadiansPerFrame);  //Rotates on the "local" Y axis
                OtherYellowCubesWorldMatrix *= Matrix.CreateTranslation(OtherYellowCubesPosition);    //Move back.
            }
            if (KBState.IsKeyDown(Keys.K))
            {
                OtherYellowCubesWorldMatrix *= Matrix.CreateTranslation(-OtherYellowCubesPosition);
                OtherYellowCubesWorldMatrix *= Matrix.CreateRotationY(CubeRotationSpeedInRadiansPerFrame);  //Rotates on the "local" Y axis
                OtherYellowCubesWorldMatrix *= Matrix.CreateTranslation(OtherYellowCubesPosition);
            }
            if (KBState.IsKeyDown(Keys.P))
            {
                OtherYellowCubesWorldMatrix *= Matrix.CreateTranslation(-OtherYellowCubesPosition);
                OtherYellowCubesWorldMatrix *= Matrix.CreateRotationX(CubeRotationSpeedInRadiansPerFrame);  //Rotates on the "local" X axis
                OtherYellowCubesWorldMatrix *= Matrix.CreateTranslation(OtherYellowCubesPosition);
            }
            if (KBState.IsKeyDown(Keys.I))
            {
                OtherYellowCubesWorldMatrix *= Matrix.CreateTranslation(-OtherYellowCubesPosition);
                OtherYellowCubesWorldMatrix *= Matrix.CreateRotationX(-CubeRotationSpeedInRadiansPerFrame);  //Rotates on the "local" X axis
                OtherYellowCubesWorldMatrix *= Matrix.CreateTranslation(OtherYellowCubesPosition);
            }
            if (KBState.IsKeyDown(Keys.OemComma))
            {
                OtherYellowCubesWorldMatrix *= Matrix.CreateTranslation(-OtherYellowCubesPosition);
                OtherYellowCubesWorldMatrix *= Matrix.CreateRotationZ(CubeRotationSpeedInRadiansPerFrame);  //Rotates on the "local" Z axis
                OtherYellowCubesWorldMatrix *= Matrix.CreateTranslation(OtherYellowCubesPosition);
            }
            if (KBState.IsKeyDown(Keys.OemQuestion))
            {
                OtherYellowCubesWorldMatrix *= Matrix.CreateTranslation(-OtherYellowCubesPosition);
                OtherYellowCubesWorldMatrix *= Matrix.CreateRotationZ(-CubeRotationSpeedInRadiansPerFrame);  //Rotates on the "local" Z axis
                OtherYellowCubesWorldMatrix *= Matrix.CreateTranslation(OtherYellowCubesPosition);
            }

            //Make Blue Sphere orbit OtherYellowCube. It orbits because we are translating it by the position of OtherYellowCube instead of it's own position from the origin.
            BlueSpheresWorldMatrix *= Matrix.CreateTranslation(-OtherYellowCubesWorldMatrix.Translation);
            BlueSpheresWorldMatrix *= Matrix.CreateRotationY(0.01f);
            BlueSpheresWorldMatrix *= Matrix.CreateTranslation(OtherYellowCubesWorldMatrix.Translation);

            //These matrices are applied from outside to inside.
            Camera = CameraPositionWorldMatrix * CameraMountWorldMatrix * YellowCubesWorldMatrix;   //Define the point where the camera is relative to Yellow Cube.
            CameraMount = CameraMountWorldMatrix * YellowCubesWorldMatrix;  //This position is where the camera "boom" is attached and is always where the camera looks.
            
            //ViewMatrix = Matrix.CreateLookAt(Camera.Translation, CameraMount.Translation, Camera.Up);
            //ViewMatrix = LookAt(YellowCubesWorldMatrix.Translation + (YellowCubesWorldMatrix.Up * 1.5f) + (YellowCubesWorldMatrix.Backward * 4f),
            //      YellowCubesWorldMatrix.Translation + (YellowCubesWorldMatrix.Up * 1.5f) + YellowCubesWorldMatrix.Forward,
            //      YellowCubesWorldMatrix.Up);
            ViewMatrix = LookAt(Camera.Translation, CameraMount.Translation, Camera.Up);



            base.Update(gameTime);
        }
        //==========================================================================================================

        
        protected override void Draw(GameTime gameTime)
        //==========================================================================================================
        //  Draw()
        //
        //  Purpose: Draw the 4 objects on the screen.
        //
        //  Parameters:
        //      gameTime - Standard XNA.
        //
        //  Notes:
        //      This Draw method is very straight forward. All it does is set the world matrix for each object. Set up
        //  some directional lighting to help make it look 3D and then draw all 4 objects. Once each mesh has its
        //  shader(s) setup to draw correctly, the model is called to Draw itself. This is repeated for each of the 4
        //  models.
        //
        //==========================================================================================================
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            //Draw the ground plane.
            foreach (ModelMesh Mesh in GroundPlane.Meshes)
            {
                foreach (BasicEffect Shader in Mesh.Effects) //Define an "effect" to draw our model with.
                {
                    Shader.World = GroundPlanesWorldMatrix;
                    Shader.View = ViewMatrix;            
                    Shader.Projection = ProjectionMatrix;
                    Shader.LightingEnabled = true;
                    Shader.EnableDefaultLighting();
                    Shader.AmbientLightColor = Color.Gray.ToVector3();     
                    Shader.DiffuseColor = Color.White.ToVector3();
                    Shader.SpecularColor = Color.White.ToVector3();
                }
                Mesh.Draw();  //Draw the mesh
            }

            //Draw the Yellow Cube. (The one the camera is attached to.)
            foreach (ModelMesh Mesh in YellowCube.Meshes)
            {
                foreach (BasicEffect Shader in Mesh.Effects) //Define an "effect" to draw our model with.
                {
                    Shader.World = YellowCubesWorldMatrix;
                    Shader.View = ViewMatrix;
                    Shader.Projection = ProjectionMatrix;
                    Shader.LightingEnabled = true;
                    Shader.EnableDefaultLighting();
                    Shader.AmbientLightColor = Color.Gray.ToVector3();     
                    Shader.DiffuseColor = Color.White.ToVector3();
                    Shader.SpecularColor = Color.White.ToVector3();
                }
                Mesh.Draw();  //Draw the mesh
            }



            //Draw the Other Yellow Cube.
            foreach (ModelMesh Mesh in OtherYellowCube.Meshes)
            {
                foreach (BasicEffect Shader in Mesh.Effects) //Define an "effect" to draw our model with.
                {
                    Shader.World = OtherYellowCubesWorldMatrix;
                    Shader.View = ViewMatrix;
                    Shader.Projection = ProjectionMatrix;
                    Shader.LightingEnabled = true;
                    Shader.EnableDefaultLighting();
                    Shader.AmbientLightColor = Color.Gray.ToVector3();
                    Shader.DiffuseColor = Color.White.ToVector3();
                    Shader.SpecularColor = Color.White.ToVector3();
                }
                Mesh.Draw();  //Draw the mesh
            }


            //Draw the Blue Sphere.
            foreach (ModelMesh Mesh in BlueSphere.Meshes)
            {
                foreach (BasicEffect Shader in Mesh.Effects) //Define an "effect" to draw our model with.
                {
                    Shader.World = BlueSpheresWorldMatrix;
                    Shader.View = ViewMatrix;
                    Shader.Projection = ProjectionMatrix;
                    Shader.LightingEnabled = true;
                    Shader.EnableDefaultLighting();
                    Shader.AmbientLightColor = Color.Gray.ToVector3();
                    Shader.DiffuseColor = Color.White.ToVector3();
                    Shader.SpecularColor = Color.White.ToVector3();
                }
                Mesh.Draw();  //Draw the mesh
            }

            base.Draw(gameTime);
        }
        //==========================================================================================================
    }
}



This post has been edited by BBeck: 02 August 2013 - 04:04 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1