- Home /
Making RigidBody face direction for movement
so i have a gameobject with a rigidbody attached and it currently moves fine with the code i have, the problem is that when it moves from input currently it doesnt face the direction its moving, i tried to fix this by adding some rotation code but this messes up the movement as it turns does stuff like the player moving forward whilst facing the opposite way, so my question is how do i make the gameobject face the way its going so that what ever direction is pressed the player rotates to that direction then goes forward in that direction, if that makes sense.
heres my code below with the non working rotation code included for abit of context
void FixedUpdate()
{
myMove = new Vector3(ControllerInputs.controllerInputs.LeftLR, 0,
ControllerInputs.controllerInputs.LeftUD);
if (grounded)
{
Quaternion rotation = Quaternion.LookRotation(myMove, Vector3.up);
transform.rotation = rotation;
targetVelocity = myMove;
targetVelocity = transform.TransformDirection (targetVelocity);
targetVelocity *= speed;
Vector3 velocity = rigidbody.velocity;
Vector3 velocityChange = (targetVelocity - velocity);
velocityChange.x = Mathf.Clamp (velocityChange.x, -maxVelocityChange,
maxVelocityChange);
velocityChange.z = Mathf.Clamp (velocityChange.z, -maxVelocityChange,
maxVelocityChange);
velocityChange.y = 0;
rigidbody.AddForce (velocityChange, ForceMode.VelocityChange);
if (canJump)
{
if(Input.GetButtonDown ("Jump"))
{
rigidbody.velocity = new Vector3 (velocity.x, CalculateJumpVerticalSpeed (), velocity.z);
}
rigidbody.AddForce (new Vector3 (0, -gravity * rigidbody.mass, 0));
grounded = false;
}
void OnCollisionStay(Collision col)
{
if(col.transform.name == "Plane")
grounded = true;
}
float CalculateJumpVerticalSpeed()
{
return Mathf.Sqrt (2 * jumpHeight * gravity);
}
Answer by cornell-lindsay · Mar 07, 2015 at 05:47 PM
after some trial and error i have the code doing what i wanted, i deleted the line changing target velocity into local coordinates and this seemed to fix the problem.
Your answer
Follow this Question
Related Questions
How to make a RigidBody not go into ground when tilted foward? 2 Answers
Player movement in the direction of rotation INACCURATE? 3 Answers
How to make rigidbody movement without changing or clamping the Velocity? 3 Answers
Rotate object towards target without influencing AddForce 0 Answers
Change movement speed based on rotation 0 Answers