- Home /
I need help with my character's rotation script
I need help with a player movement script that I'm using for the character's rotation. It works alright, but I've ran into 2 problems with it: 1) The player moves diagonally when I press the A & D keys. 2) When wanting to move down by pressing S, the character turns in the direction, but he doesn't move. I've only recently gotten into coding, so I'm not sure what the problem is. If someone could help, that would be amazing.
Here's the code:
public class Player : MonoBehaviour {
public float movementSpeed = 10f;
void Update()
{
ControllPlayer();
}
void ControllPlayer()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
if (moveHorizontal == 0 && moveVertical == 0) return;
Vector3 movement = new Vector3(moveHorizontal, 0f, moveVertical);
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(movement), 0.15F);
if (movement != Vector3.zero)
{
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(movement.normalized), 0.2f);
}
transform.Translate(movement * movementSpeed * Time.deltaTime, Space.World);
}
}
Answer by Santa · Jun 11, 2020 at 08:30 PM
The problem is here:
transform.Translate(movement * movementSpeed * Time.deltaTime, Space.World);
You are moving in direction of 'movement' in World-space but it is not a World-space vector. In your case it is better to just move 'forward':
transform.Translate(transform.forward * movementSpeed * Time.deltaTime, Space.World);
Also not to the topic of your question but the line 'if (movement != Vector3.zero)' is useless. You are checking it in line 'if (moveHorizontal == 0 && moveVertical == 0) return;'.
Unfortunately, the changes didn't work for some reason, but thank you so much for trying to help me! I appreciate it.
Also, thank you for the extra help. I'll try to keep that in $$anonymous$$d if I use this script again.
'forward' is blue axis. $$anonymous$$ay be your transform rotated somehow that it is pointing into the ground collider or some other collider?
Your answer
![](https://koobas.hobune.stream/wayback/20220613000702im_/https://answers.unity.com/themes/thub/images/avi.jpg)