- Home /
make player move in direction it's facing
Hello to all, currently I am having issues making my player move in the direction of its rotation. For some reason it only wants to move in the first direction it was facing. I would like it to continue to only move by hoping. Thanks in advance!
public GameObject player;
public float speed = 7.0f;
public float rotateSpeed = 3.0f;
void Update()
{
//Moves player upwards
if (Input.GetAxis("Vertical") == 1)
{
var move = new Vector3(0, Input.GetAxis("Vertical"), 0);
transform.Translate(transform.up * speed * Time.smoothDeltaTime);
}
//Rotates player direction
if (Input.GetAxis("HorizontalTurn") > 0)
transform.Rotate(Vector3.up * 90 * Time.deltaTime);
else if (Input.GetAxis("HorizontalTurn") < 0)
transform.Rotate(Vector3.up * -90 * Time.deltaTime);
//launches player forward based on momentum from left stick and facing direction of right
if (Input.GetAxis("rightTrigger") == 1 && Input.GetAxis("Vertical") == 1)
{
transform.position += Vector3.forward * Time.deltaTime * speed;
}
}
}
Use transform.forward to get the direction player is facing
Answer by Soujiro-Senpai · May 26, 2017 at 04:18 PM
Use Rigidbody to make it easy:
public float movementSpeed = 10f;
Vector3 movement;
Rigidbody rigidbody;
void Awake()
{
rigidbody = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Horizontal");
MoveCharacter(horizontal, vertical);
}
void MoveCharacter(horizontal, vertical)
{
movement.Set(horizontal, 0, vertical);
if (horizontal != 0 || vertical != 0)
{
rigidbody.MoveRotation(Quaternion.LookRotation(movement));
}
movement = movement.normalized * movementSpeed * Time.deltaTime;
rigidbody.MovePosition(transform.position + movement)
}
That's the code if I remember it right. Haha
Answer by R4mbi · May 26, 2017 at 09:56 AM
You should move your player with a Rigidbody.
transform.Translate is more like teleportation and doesn't always collide correctly with objects.
To move your player according to its rotation, use the Rigidbody.AddRelativeForce method.
Your answer
Follow this Question
Related Questions
Game Object won't match rotation of new positions transform 1 Answer
How to make Camera position Independent of its Rotation? 1 Answer
How do you make a player move on a remote items local axis? 0 Answers
[solved] Get upward orientation of object and add scale value 1 Answer
setting transform physics2d issue 0 Answers