Player not changing direction when I turn
I want my player (a spherical ball) to change the direction in which it travels when I turn (which is done through a small rotation). For example, if I turn left using the "a" key, then that becomes the new forward direction to travel in when I pres the "w" key. However, I can't get this to work even after searching other forum posts and answers. Any help would be appreciated, thanks.
My Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public Rigidbody rb;
public float forwardForce = 1000f;
public float backwardForce = -400f;
public float turnSpeed = 1f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKey("w")) {
rb.AddRelativeForce(0, 0, forwardForce * Time.deltaTime);
}
if (Input.GetKey("s")) {
rb.AddRelativeForce(0, 0, backwardForce * Time.deltaTime);
}
if (Input.GetKey("a")) {
transform.Rotate(0f, turnSpeed * Time.deltaTime, 0f, Space.Self);
}
if (Input.GetKey("d")) {
transform.Rotate(0f, -turnSpeed * Time.deltaTime, 0f, Space.Self);
}
}
}
Edit: I was able to find something that helps move the ball however it does not rotate the ball when moving (which is why I was originally using AddForce instead of transform.Translate). Is there a way to use this new code but add rotation into it without the rotation messing up the direction in which the ball is travelling?
My updated Code for above:
if (Input.GetKey("w")) {
transform.Translate(Vector3.forward * movementSpeed * Time.deltaTime);
}
if (Input.GetKey("s")) {
transform.Translate(-Vector3.forward * movementSpeed * Time.deltaTime);
}
if (Input.GetKey("a")) {
transform.Rotate(Vector3.up, -turnSpeed * Time.deltaTime);
}
if (Input.GetKey("d")) {
transform.Rotate(Vector3.up, turnSpeed * Time.deltaTime);
}
Comment