- Home /
How do you move a rigidbody by a vector3 relative to itself?
When I try and move a rigidbody with the MovePosition(Vector3) function, it moves in the direction of that actual vector3. I want it to move by that vector3 in the direction the rigidbody is already facing. here's my current code. What would I use to do this correctly?
void FixedUpdate ()
{
//Take input for movement
Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));
movement *= speed;
//Move
rigidbody.MovePosition (rigidbody.position + movement * Time.deltaTime);
//Take input for rotation
Vector3 rotation = new Vector3( 0f, Input.GetAxis("Turn"), 0f);
rotation *= rotateSpeed;
//Rotate
rigidbody.MoveRotation (transform.rotation * Quaternion.Euler(rotation));
}
Your question as stated does not make much sense to me. You cannot both move in the direction the rigidbody is facing and also move 'by the vector3'. That is a vector3 is a direction. You could rewrite the character so that it always moves to its forward and it uses Input.GetAxis("Vertical") to calculate forward movement. Or?
So is this code the answer to your question (it looks like it to me). If so, promote it from a comment to an answer and mark your question answered by clicking on the checkmark on the right side of your answer.
Answer by dustxx · Feb 23, 2014 at 05:35 AM
ah, yeah. I realized that a bit after posting this question and I rewrote it to move based on the forward. Like this:
//Take input for rotation
Vector3 rotation = new Vector3( 0f, Input.GetAxis("Turn"), 0f);
rotation *= rotateSpeed;
//Rotate
rigidbody.MoveRotation (transform.rotation * Quaternion.Euler(rotation));
//Take input for vertical movement
float moveVert = Input.GetAxis ("Vertical");
moveVert *= speed;
//Move vertically
rigidbody.MovePosition (rigidbody.position + (transform.forward * moveVert) * Time.deltaTime);
//Take input for horizontal movement
float moveHorz = Input.GetAxis ("Horizontal");
moveHorz *= speed;
//Move horizontally
rigidbody.MovePosition (rigidbody.position + (transform.right * moveHorz) * Time.deltaTime);
Sorry if the orighinal question was confusing
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Character controller jittering up and down 2 Answers
A simple solution for constant rigidbody movement without changing and clamping velocity directly 2 Answers
Move the rigidbody with keys 1 Answer
How to code PlayerController grid movement with RigidBody and Colliders? 1 Answer