Hi! I’ve been at this for a few days now, learning about how to get a character controller working properly. Everything works as expected now, except for the fact that my character won’t move forward based on the current rotation, that is, based on the direction the rotated player is facing (see image further down).
When I press ‘w’ and ‘s’, the character always moves in the same direction, forwards or backwards according to how they were positioner at start. ‘a’ and ‘d’ are used for rotating the character.
This is the Script I’ve cooked up so far, it is the result of a combination of 2-3 tutorials. (HorizontalL and VerticalL are named like that on purpose).
using UnityEngine;
public class MovementControllerMedium : MonoBehaviour
{
// Grund koden för basic movement kommer medium, Adam Davis.
[SerializeField] private float speed = 5f;
[SerializeField] private float jumpHeight = 15f;
[SerializeField] private float gravity = 0.5f;
[SerializeField] private float rotationSpeed = 180f;
private CharacterController controller;
private float yVelocity;
private Vector3 rotation;
// Start is called before the first frame update
void Start()
{
controller = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update()
{
float horizontalInput = Input.GetAxis("HorizontalL");
float verticalInput = Input.GetAxis("VerticalL");
rotation = new Vector3(0, Input.GetAxisRaw("HorizontalL") * rotationSpeed * Time.deltaTime, 0);
Vector3 direction = new Vector3(0, 0, verticalInput);
Vector3 velocity = direction * speed;
if (controller.isGrounded)
{
if (Input.GetKeyDown(KeyCode.Space))
{
yVelocity = jumpHeight;
}
}
else
{
if (Input.GetKeyDown(KeyCode.Space))
{
yVelocity += jumpHeight;
}
yVelocity -= gravity;
}
velocity.y = yVelocity;
controller.Move(velocity * Time.deltaTime);
transform.Rotate(rotation);
}
}
From what I understand, I have to use transform.forward in some way in order to get the result I want, but I have no clue how.
The black arrow is the direction the cylinder is moving when pressing down ‘w’, the red arrow is the direction the cylinder is facing as a result of pressing down the ‘d’ key, the direction I want the player to move towards.
Any and all help is appreciated, but I would rather have a solution that works with the code I already got. I feel like it should be very simple, but that I am missing something.