Lynnstrum - 1 year ago 66
C# Question

# Turn player 90 degrees on mouse click

I'm making a simple runner game and I'm trying to make it so when you click the mouse it turns the player 90 degrees, and he then runs in that direction.
So if you're running straight, click the mouse you're now running to the left. etc. The player runs, and when I click the mouse button he turns, however the first time is 90 degrees, the second time is more like 60 degrees, then the 3rd is back to 90, and finally the fourth is 60 degrees(roughly) once again.
My question is; Judging by this code, why are two of the clicks outputting 90 degrees, while the other two are not? Even though every click is based off the same code. Also if I could optimize my code any that'd be greatly appreciated. This is the first time I've tried to make a system like this.
Note:

``````controller.Move (moveVector * Time.deltaTime);// Move the player
transform.Translate (moveVector * (speed) * Time.deltaTime); // Move on player axis instead of world axis.
``````

Are both used because with just controller.Move my player only runs straight
and with only transform.Translate my player falls through the ground forever.
Here is the code I have so far:

``````using UnityEngine;
using System.Collections;
public class PlayerMotor : MonoBehaviour
{
private CharacterController controller;
private Vector3 moveVector;
private float speed = 2.0f;
private float verticalVelocity = 0.0f;
private float gravity = 12.0f;
void Start()
{
controller = GetComponent<CharacterController> ();
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
transform.Rotate(new Vector3(0, -90, 0));
}
moveVector = Vector3.forward;
if (controller.isGrounded)
{
verticalVelocity = -0.5f;
}
else
{
verticalVelocity -= gravity * Time.deltaTime;
}
moveVector.x = Input.GetAxisRaw ("Horizontal") * speed;
moveVector.y = verticalVelocity;
moveVector.z = speed;
controller.Move (moveVector * Time.deltaTime);
transform.Translate (moveVector * (speed) * Time.deltaTime);
}
}
``````

The rotation of your player is nothing to do with how your player is moving. The actual moving path is determined by the position of the player and the `moveVector` only.

With just controller.Move my player only runs straight.

That's because the moveVector is always (0.0, -0.5, 2.0).

If I am not mistaken, you want the player to move towards the direction it faces, right? You can achieve that by using a moveVector like below.

``````    moveVector.x = transform.forward.x * speed;
moveVector.y = verticalVelocity;
moveVector.z = transform.forward.z * speed;
``````

Remove the `transform.Translate` line.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download