- Home /
I am having issue with my third person controller. How do I make the camera rotate with my object, but also keep a certain distance away from that same object.
I am new to unity so I was working on one of the tutorials in unity Learn. I finished the tutorial which covered how to make the player move in a third person view. But one question I had was the camera controller would not adjust for a car turning to the left or right. So I set out to try and code this myself. In this tutorial they told us how to make the car rotate and and to move the cameras up and down the z axis in a straight line. So I used a rotate function to move my camera. But the issue was that I can not keep the distance needed to keep my car in view. I want this to be a third person controller. But if I can not have the camera stay a set distance it will not work. The issue is I have no idea how to do this. Please Make your response easy to understand. Also, Explain how it works so I can use it in the future. An Important note, when the car is in its start position it works fine. Only when I turn it is where I have the issue. The offset variable works only when the car is in a straight line.
This is the Cameras Code
public class FollowPlayer : MonoBehaviour
{
public GameObject player;
private Vector3 offset = new Vector3(0,5,-7);
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.position = player.transform.position + offset;
transform.rotation = player.transform.rotation;
}
}
This is the Cars code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float speed = 15.0f;
public float turnSpeed;
public float horizontalInput;
public float forwardInput;
// Start is called before the first frame update
void Start()
{
turnSpeed = 50;
}
// Update is called once per frame
void Update()
{
horizontalInput = Input.GetAxis("Horizontal");
forwardInput = Input.GetAxis("Vertical");
// Move the vehicle Forward
transform.Translate(Vector3.forward * Time.deltaTime * speed * forwardInput);
transform.Rotate(Vector3.up * turnSpeed * horizontalInput * Time.deltaTime);
}
}
Answer by MUG806 · Feb 15, 2021 at 01:54 PM
If you want the camera to perfectly follow the player, the simplest way is to make the camera a child of the player. Simply click and drag the main camera in your hierarchy onto the player. Then move the camera to the desired position, and that relative position will be maintained as the player moves.
Your answer
Follow this Question
Related Questions
How do you use mesh colliders on third person controller 0 Answers
How to rotate smoothly behind target? 0 Answers
How to identify ThirdPersonCharacters activities like walking, running, jumping in unity5 0 Answers
Run animation click/touch to move problem 0 Answers
ThirdPersonController character hovers above capsule collider 2 Answers