Hey there, I’ve seen this issue discussed widely on unity but as a starter I don’t quite understand it.
When I comes to movement via WASD, if I turn around the WASD is locked and doesn’t “adapt” to the direction I’m looking at.
I’d like a sort of explanation as to why this is an issue, and some sort of code I can possibly use to fix this.
I have both a player and virtual camera, the camera is locked with the player.
The camera’s aim is POV, and its body is Hard Lock To Target.
Currently, this is my movement code vv
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
Rigidbody rb;
float movementSpeed = 6f;
// Start is called before the first frame update
//woah! this is code
void Start()
{
rb = GetComponent();
}
// Update is called once per frame
//good for movement!!
void Update()
{
float horizontalInput = Input.GetAxis(“Horizontal”);
float verticalInput = Input.GetAxis(“Vertical”);
rb.velocity = new Vector3(horizontalInput * movementSpeed, rb.velocity.y, verticalInput * movementSpeed);
if (Input.GetButtonDown(“Jump”))
{
rb.velocity = new Vector3(rb.velocity.x, 5f, rb.velocity.z);
}
}
You should rotate your input vector according to body rotation. There are different ways to do so, but I prefer something like that.
You should first implement body rotation logic (rotation around Y axis), and then multiply input vector like so:
var input = new Vector3(Hor, 0, Vert)
input = body.rotation * input;
When working with physics you’ll need to update the rigidbody in FixedUpdate instead of Update. I recommend you do a search for controller scripts and learn from them. Some people may suggest you just use a script that has already been written but I believe it’s good to learn about all the intricacies for yourself.
A slightly modified version of your script:
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
Rigidbody rb;
float movementSpeed = 6f;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
Vector3 force=(transform.right*Input.GetAxisRaw("Horizontal")+transform.forward*Input.GetAxisRaw("Vertical")).normalized * movementSpeed;
rb.AddForce(force);
if (Input.GetButton("Jump"))
{
rb.AddForce(Vector3.up*100);
}
}
}
I went through quite a lot of posts on this issue but I’ve never found a good place to start.
But I appreciate this help! I think I understand a little better now
I’m going to either try this or some other things I’ve seen (likely this, as this is more specific to my code)