Im making a 3d game that involves my player running in different directions. My controller is a joystick. I need a way to get my player to face the direction its moving in. At the moment, it’s face foward for all the directions. Please help me. A script would help because I am still a beginner at coding. Thanks in advance!
public class Mymovement : MonoBehaviour {
public float moveSpeed;
public VirtualJoystick joystick;
// Update is called once per frame
void Update()
{
transform.Translate(moveSpeed * Input.GetAxis("Horizontal") * Time.deltaTime, 0f, moveSpeed * Input.GetAxis("Vertical") * Time.deltaTime);
transform.Translate(joystick.inputVector.x * moveSpeed * Time.deltaTime, 0, joystick.inputVector.z * moveSpeed * Time.deltaTime);
}
}
As a programmer, it is your job to come up with a solution, we can only show you the direction towards the right path. As for how you would get your player to face the direction in which it is moving, you will either need to match the rotation property with the velocity and/or look vector or with the input vector (the latter faces difficulty when moving in 3rd space as joystick input is a 2 dimensional vector, meaning you’d actually have to take into account a second joystick, and 2 things are harder than sometimes 2).
As for how you implement this (animation, state etc.) is completely up to you. For a 2D game you can simply use cotangent / tangent calculation to index 2^n-axis directions as you won’t have infinite sprites for infinite angles. For a 3D game, you’d use the purely vector approach.
You’ll want to use the same inputs from your movement to also determine the rotation for the object. So for example you can have a Horizontal input of 1 and a Vertical input for -1. In this case we have the player moving right and down at a 45 degree angle, we’ll also want the player angled at 45 degrees to match. You can create a new vector for where the player is moving and set the rotation to that object.
float moveHorizontal = Input.GetAxisRaw ("Horizontal");
float moveVertical = Input.GetAxisRaw ("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
transform.rotation = Quaternion.LookRotation(movement);
transform.Translate (movement * movementSpeed * Time.deltaTime, Space.World);
This answer was provided by @PaxForce in another thread so I just stole the code example he provided to give an idea for how to accomplish this.