Jump to content
  • Advertisement
Sign in to follow this  
football94

Making a 3D model face the direction it's moving

This topic is 2142 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi guys

 

Ive been experimenting with the xna skinning sample(link below) and have begun trying to implement controller/keyboard input, right now Im able to move the model forward,backwards, left, and right but after different approaches I havent been able to find info on how to get the model to face the direction in which it is moving if anyone could point me in the right direction on how this is done it would be much appreciated.(the code I have so far is below)

 

                     

                                                 Thankyou

 

 

 

 

 

skinning sample link

http://xbox.create.msdn.com/en-US/education/catalog/sample/skinned_model

 

 

 

below is what I have so far in the draw method

 protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice device = graphics.GraphicsDevice;

            device.Clear(Color.CornflowerBlue);

            Matrix[] bones = animationPlayer.GetSkinTransforms();
            for (int i = 0; i < bones.Length; i++)
            {
                bones[i] *=
                      Matrix.CreateRotationX(Rotation.X) //Computes the rotation
                    * Matrix.CreateRotationY(Rotation.Y)
                    * Matrix.CreateRotationZ(Rotation.Z)
                    * Matrix.CreateTranslation(position)
                    * Matrix.CreateWorld(Translation, Vector3.Forward, Vector3.Up); //Move the models position
            }
            

          

           
            Matrix[] modelTransforms = new Matrix[currentModel.Bones.Count];
            currentModel.CopyAbsoluteBoneTransformsTo(modelTransforms);

            // Render the skinned mesh.
            foreach (ModelMesh mesh in currentModel.Meshes)
            {
                foreach (Effect effect2 in mesh.Effects)
                {
                   
                    
                    effect2.Parameters["Bones"].SetValue(bones);
                    effect2.Parameters["View"].SetValue(camera.viewMatrix);
                    effect2.Parameters["Projection"].SetValue(camera.projectionMatrix);
                    
                   
                }

                mesh.Draw();

                DrawCity();
                drawDebug();
                fine1();
                
                
            }

            base.Draw(gameTime);
        }

this is what I have so far for the input method

private void HandleInput(GameTime gameTime)
        {
            KeyboardState currentKeyboardState = Keyboard.GetState();

            // Check for exit.
            if (currentKeyboardState.IsKeyDown(Keys.Escape))
            {
                Exit();
            }

            float speed = 0.02f; //Dictates the speed
            if (currentKeyboardState.IsKeyDown(Keys.Left))
            {
                position.Z -= speed * (float)gameTime.ElapsedGameTime.TotalMilliseconds;
              
            }
            if (currentKeyboardState.IsKeyDown(Keys.Right))
            {
                position.Z += speed * (float)gameTime.ElapsedGameTime.TotalMilliseconds;
            }
            if (currentKeyboardState.IsKeyDown(Keys.Up))
            {
                position.X += speed * (float)gameTime.ElapsedGameTime.TotalMilliseconds;
            }
            if (currentKeyboardState.IsKeyDown(Keys.Down))
            {
                position.X -= speed * (float)gameTime.ElapsedGameTime.TotalMilliseconds;
            }
           
           
          

        
        }

Share this post


Link to post
Share on other sites
Advertisement

Hi football94!

You can calculate the rotation between the two world points (Vector3) 

This is what I used in my game:

	public Quaternion GetRotation(Vector3 targetPos)
		{
			return GetRotation(this.Position, targetPos);
		}

		public Quaternion GetRotation(Vector3 entityPos, Vector3 targetPos)
		{
			// the new forward vector, so the avatar faces the target
			Vector3 newForward = Vector3.Normalize(entityPos - targetPos);

			// calc the rotation so the avatar faces the target
			var src = Vector3.Forward;

			var dest = newForward;

			src.Normalize();
			dest.Normalize();

			float d = Vector3.Dot(src, dest);

			if (d >= 1f)
			{
				return Quaternion.Identity;
			}
			if (d < (1e-6f - 1.0f))
			{
				Vector3 axis = Vector3.Cross(Vector3.UnitX, src);

				if (axis.LengthSquared() == 0)
				{
					axis = Vector3.Cross(Vector3.UnitY, src);
				}

				axis.Normalize();
				return Quaternion.CreateFromAxisAngle(axis, MathHelper.Pi);
			}


			float s = (float)Math.Sqrt((1 + d) * 2);
			float invS = 1 / s;

			Vector3 c = Vector3.Cross(src, dest);
			Quaternion q = new Quaternion(invS * c, 0.5f * s);
			q.Normalize();

			return q;
		}

when drawing your model use:

NewPosition = should be the target (future) position that your model is moving towards.


Quaternion RotationQuat = GetRotation(NewPosition);

 

then you need to store your RotationQuat and do NOT update it until your new "future" position is changed.

otherwise the model will rotate back the moment you stop moving.

for (int i = 0; i < bones.Length; i++)
{
bones[i] *=
Matrix.CreateFromQuaternion(RotationQuat)
* Matrix.CreateTranslation(position)
* Matrix.CreateWorld(Translation, Vector3.Forward, Vector3.Up); //Move the models position
...

I hope this helped :)

Share this post


Link to post
Share on other sites

Please don't use all caps for your thread titles, it makes it look like you're yelling at everyone. smile.png

Share this post


Link to post
Share on other sites

Hi.

heres a not so wright way of doing it it works with x , z y should be set to 0.

 

first you need to define a 3dvector for the direction the mesh was facing when exported.

only set UnitsFacingDirection at init time when you create your asset

 

D3DXVECTOR3 toTarget = UnitsFacingDirection;

 

D3DXVec3Normalize(&toTarget,

&toTarget);

 

D3DXVec3Normalize(&vHeading, &vHeading);//vheading is the vector you should have for the motion of the object

 

 

 

//first determine the angle between the heading vector and the target

 

//double angle = acos(m_vHeading.Dot(toTarget));

FLOAT dot = D3DXVec3Dot(&vHeading, &toTarget);//this bit is a bit off needs fixing

dot = Clamp( dot, - 1.0f, 1.0f );

 

double Angle = acos(dot);

 

 

//return if the player is facing the target

 

if(Angle < 0.00001)

 

return;

 

 

//The next few lines use a rotation matrix to rotate the player's heading

//vector accordingly

 

//notice how the direction of rotation has to be determined when creating

//the rotation matrix

 

 

 

int s = Sign(vHeading, toTarget);

 

D3DXMatrixRotationY(&Rotation, Angle * s);

 

and that rotates it about the Y axis.

 

 

//------------------------ Sign ------------------------------------------

//

// returns positive if v2 is clockwise of this vector(v1),

// minus if anticlockwise (Y axis pointing down, X axis to right)

//------------------------------------------------------------------------

enum

 

{clockwise = 1, anticlockwise = -1};

int

 

Sign(const D3DXVECTOR3& v1, const D3DXVECTOR3& v2);

 

int Sign(const D3DXVECTOR3& v1, const D3DXVECTOR3& v2)

{

 

if (v1.z*v2.x > v1.x*v2.z)

{

 

return anticlockwise;

}

 

else

{

 

return clockwise;

}

blink.png

Share this post


Link to post
Share on other sites

Please don't use all caps for your thread titles, it makes it look like you're yelling at everyone. smile.png

 

 

laugh.png So sorry I had no idea, and I appreciate the replies to my post thanks guys Ill let you know what I come up with.
 

Share this post


Link to post
Share on other sites

 It Worked!!!

 

Thanks Zerratar that worked perfectly!

 

code below is just a small sample of how I tested it

 

 

Vector3 NewPosition = new Vector3(55, 0, 77);

  if (currentKeyboardState.IsKeyDown(Keys.Left))
            {
               
                RotationQuat = GetRotation(NewPosition); 
            }

and Thanks again guys for responding to my post biggrin.png

Share this post


Link to post
Share on other sites

 It Worked!!!

 

Thanks Zerratar that worked perfectly!

 

code below is just a small sample of how I tested it

 

 

Vector3 NewPosition = new Vector3(55, 0, 77);

  if (currentKeyboardState.IsKeyDown(Keys.Left))
            {
               
                RotationQuat = GetRotation(NewPosition); 
            }

and Thanks again guys for responding to my post biggrin.png

Hurray! I'm glad it worked for you! :)

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!