How to make a camera follow a ball from behind? c#
Hello!
Im having some problems making the camera turn with the ball. https://youtu.be/6D337xSoQV4 in the YouTube link you can see the camera is following the ball but only show it from the same angle. I would like the camera to turn with the ball, so the backside of the ball is seen and it's possible for the player to see the road ahead.
the code for the camers:
using UnityEngine; using System.Collections;
public class FollowBall : MonoBehaviour {
public GameObject player;
private Vector3 offset;
void Start () {
offset = transform.position;
}
void LateUpdate () {
transform.position = player.transform.position + offset;
}
}
I dont know if it's needed but i have also added the code for the ball (PlayerController):
using UnityEngine; using System.Collections;
public class PlayerController : MonoBehaviour {
private Rigidbody rb;
void Start (){
rb = GetComponent<Rigidbody> ();
}
// Update is called once per frame
void FixedUpdate () {
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
rb.AddForce (movement);
}
}
Hope someone have the answer! :)
Answer by Castermaluney · May 17, 2016 at 05:49 PM
this should work:
public GameObject player;
private Vector3 _offset;
void Start()
{
_offset = new Vector3 (0, y, z); //just put the values that you want instead of y and z
}
void FixedUpdate()
{
Vector3 flatSpeed = player.rigidbody.velocity;
flatSpeed.y = 0;
//stores the flat velocity of your player so it can put the camera always behind it
Quaternion wantedRotation;
if (flatSpeed != Vector3.zero)
{
float targetAngle = Quaternion.LookRotation(flatSpeed).eulerAngles.y;
wantedRotation = Quaternion.Euler(0, targetAngle, 0);
}
tranform.position = player.transform.position + (wantedRotation * _offset);
transform.LookAt(player.transform);
}
Answer by vintar · Jan 18, 2016 at 07:11 PM
Try something like this :
public GameObject Player;
Vector3 _offset;
void Start()
{
_offset = new Vector3(0, -22, 10); // or whatever you need
}
void FixedUpdate()
{
transform.position = Player.transform.position + _offset;
transform.rotation = Player.transform.rotation;
}
Answer by Otaku_Riisu · May 23, 2016 at 05:23 PM
Try parenting the main camera to the ball. It seems simple, and it is, but works surprisingly well.
If that fails, follow this tutorial. It's in the middle of a series on RPG character controllers. The camera script works quite well, and you should have a very aesthetically pleasing result.