Following player with the Camera

Hi there! If you haven’t seen the previous post (character control and moving a lot of entity), then here it is, or here are the very beginning.

Before we move on to physics, let’s make our camera to follow our player. If you not interested in it, then skip it and go to the next post.

The camera

We can’t make an entity from the camera (we can, but it wont’t render anything), so it will be a “simple” MonoBehaviour.

// Assets/Scripts/CameraFollow.cs

using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;
using UnityEngine;

public class CameraFollow : MonoBehaviour
{
  private Entity _target;
  private float3 _difference;

  private EntityManager _entityManager;

  public void SetEntityToFollow(Entity target)
  {
    _entityManager = World.Active.EntityManager;
    _target = target;

    float3 position = transform.localPosition;
    _difference = _entityManager.GetComponentData<Translation>(target).Value + position;
  }

  private void LateUpdate()
  {
    transform.localPosition = _entityManager.GetComponentData<Translation>(_target).Value + _difference;
  }
}

Despite of it’s a MonoBehaviour, we need the reference of our player entity. With the SetEntityToFollow method we save the reference of the target entity, calculate the actual position difference (my player and the camera are in the scene), and every LateUpdate, when all of our Systems are completed we update the camera’s position (if you take a look at the Entity Debugger, the PresentationSystem running in PreLateUpdate).

We have a really important class here, the EntityManager, we’ll use it much, and I’ll write about it in the next post. Now we are use it to get the ComponentData from the target entity.

PlayerProxy


// Assets/Scripts/Player/PlayerProxy.cs

using Unity.Entities;
using UnityEngine;

public class PlayerProxy : MonoBehaviour, IConvertGameObjectToEntity
{
#pragma warning disable 0649
  [SerializeField] private float _speed;
  [SerializeField] private CameraFollow _camera;
#pragma warning restore 0649

  public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
  {
    dstManager.AddComponentData(entity, new PlayerData()
    {
      Speed = _speed
    });
    _camera.SetEntityToFollow(entity);
  }
}

We are set the reference to our CameraFollow script in the Editor, and in the Convert method we are set the converted entity to it’s target. Now if we hit play, we can see that the camera will follow our player with the position difference setted in the Scene window.