When making the camera follow a ball, which one should control the camera position? The ball or the camera itself?

Viewed 69

I am learning Unity3D and now creating a trivial (useless) game as follows.

enter image description here

The ball rolls down the inclined floor and the camera must follows the ball with the following relationship

  • x camera = x ball
  • y camera = y ball + 3
  • z camera = z - 10

There are two possible ways to control the camera position.

The ball controls the camera

In this scenario, I attach the following script to the ball.

public class Ball : MonoBehaviour
{
    [SerializeField]
    private Transform cameraTransform;

    void Start() { }

    void Update()
    {
        Vector3 newCameraPos = new Vector3
        {
            x = transform.position.x,
            y = transform.position.y + 3f,
            z = transform.position.z - 10f
        };
        cameraTransform.position = newCameraPos;
    }
}

The camera controls itself

In this scenario, I attach the following script to the camera.

public class Camera : MonoBehaviour
{

    [SerializeField]
    private Transform ballTransform;

    void Start() { }


    void Update()
    {
        Vector3 newCameraPos = new Vector3
        {
            x = ballTransform.position.x,
            y = ballTransform.position.y + 3f,
            z = ballTransform.position.z - 10f
        };
        this.transform.position = newCameraPos;
    }
}

Question

Even though both methods work as expected, I am wondering whether there are any pros and cons for each method. Which one should I use?

1 Answers

As you've already mentioned, both examples work as expected.

What I like to do though, is assign functionality to the object that is responsible for performing the 'action'. In this case the camera is 'following' something. At the moment, it is following the ball, but later if you wanted to make it follow something else, would it make sense to have to navigate to your ball gameobject to change that behaviour? I think not.

By assigning functionality to objects based on 'responsibilities' you will often find that your code ends up being much more modular in the long run.

Of course this sort of practice is nothing new to game development, or software development at all. It complements the Single Responsibility Principle and shares many of its qualities.

But, at the end of the day, if you're working on your code alone, then you will know the codebase inside out. So it's up to you really!

I would also suggest creating Components based off of those responsibilities whenever possible. So instead of having one generic Camera component, I would create a FollowTarget component and attach that to the camera. In doing so, you will have enabled the ability to use that very same Component to make some other, arbitrary object follow another arbitrary object in your game.

Happy learning!

Related