1

I have a ball that move forward and bounce and rotate, and I want the camera to follow it and rotate with it so the camera always look at the ball from behind. So I made the script bellow but the camera didn't look at the ball when rotating!

NB: I didn't use camera as a child of the ball because I don't want the camera to bounce.

Camera Script:

public Transform Ball;
private Vector3 Offset;

// Use this for initialization
void Start () {

    Offset = transform.position - Ball.transform.position;

}

// Update is called once per frame
void LateUpdate () {

    transform.position = new Vector3(Ball.transform.position.x + Offset.x, transform.position.y, Ball.transform.position.z + Offset.z);
    transform.rotation = Ball.transform.rotation;
}

1 Answer 1

1
 [SerializeField]
 private Transform target;

 [SerializeField]
 private Vector3 offsetPosition;

 [SerializeField]
 private Space offsetPositionSpace = Space.Self;

 [SerializeField]
 private bool lookAt = true;

 private void Update()
 {
     Refresh();
 }

 public void Refresh()
 {
     if(target == null)
     {
         Debug.LogWarning("Missing target ref !", this);

         return;
     }

     // compute position
     if(offsetPositionSpace == Space.Self)
     {
         transform.position = target.TransformPoint(offsetPosition);
     }
     else
     {
         transform.position = target.position + offsetPosition;
     }

     // compute rotation
     if(lookAt)
     {
         transform.LookAt(target);
     }
     else
     {
         transform.rotation = target.rotation;
     }
 }

The target is your player gameobject

Sign up to request clarification or add additional context in comments.

3 Comments

@Taik then create an update function and set the cameras y position to a specific value
Go into the inspector and look at the cams y position. In the cam script create an void Update() {} function and in that insert this line of code: gameObject.transform.position = new Vector3(gameObject.transform.position.x, the float you read from the inspector, gameObject.transform.position.z);
Thank you so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.