I am building a third person game where the player is a metal ball and they have to successfully navigate through the maze.
So far, the scripts for the camera enable the Main Camera to follow the player object and when the player turns left or right, the Main Camera will rotate with it, enabling the player to see what is in front of them.
However, when the player turns around or rotates 180 degrees to face the opposite direction to what they started in, the controls for the player object do not match this rotation e.g. once rotated 180 degrees, to go forwards the player has to press backwards.
I have tried many codes from other questions and have googled the hell out of this but I still cant figure it out.
Okay, so what you’re doing now is having the rotation of the camera be completely unrelated to the movement of the ball - your script for player movement is based off world coordinates, so its forward axis will always be the same regardless of what direction the camera is facing. Instead, what you want to do is something like
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour {
private float speed;
private bool isRunning;
private Rigidbody rb;
public GameObject mainCamera;
// Use this for initialization
void Start () {
speed = 1f;
isRunning = true;
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
//void Update()
//{
//}
void FixedUpdate()
{
Vector3 fromCameraToMe = transform.position - mainCamera.transform.position;
fromCameraToMe.y = 0; // First, zero out any vertical component, so the movement plane is always horizontal.
fromCameraToMe.Normalize(); // Then, normalize the vector to length 1 so that we don't affect the player more strongly when the camera is at different distances.
//if (isRunning)
//{
// elapsedTime += Time.deltaTime;
//}
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
//Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
// We can cheat a bit here - we had to flatten out the 'forward' vector from the camera to the player, but the camera is always horizontal left-right, so we can just use
// its 'transform.right' vector to determine the direction to move the ball. Add the horizontal and vertical vectors to determine ground-plane movement.
Vector3 movement = (fromCameraToMe * moveVertical + mainCamera.transform.right * moveHorizontal) * speed;
rb.AddForce(movement * speed);
}
}