Hi, I’m doing a game inspired on Xonix to improve some skills and learn more about Unity3D.
I’m trying to do an script so that my camera follows a target, but not directly centered on it, and allowing the player to have a good perception of the grid when he is situated at the end of the grid, so he would know if there is an enemy when he comes back.
Something like in this game:
Here, in my opinion:
- the camera has a good distance from the player, it’s not centered on him (i.e., the player is not always in the middle of the screen);
- the player can know if there is an enemy when he is in the end of the grid and he decides to move to the begin of the grid;
- the camera has a dynamic distance from the player (small distance: player in the first line of the grid; large distance: player in the lest camera of the grid).
So, this is what I’m trying to do. I’ve tried some approaches and now I have this script:
public class CameraFollow : MonoBehaviour
{
// The distance that the camera will keep from the target.
Vector3 distanceFromTarget = new Vector3 (0f, 13f, -10f);
// The target.
[SerializeField]
Transform Target;
// A thereshold to define when the camera has to move.
int threshold = 10;
// The time to accomplish the movement.
float journeyTime = 12.0F;
// The time when the camera starts to follow the target.
float startTime;
// The camera is already following the target?
bool following = false;
void Start ()
{
//First let's start with our Camera Centered on our Player
transform.position = Target.position + distanceFromTarget;
}
void Update ()
{
float dist = Vector3.Distance (this.transform.position, Target.transform.position);
if (dist >= threshold && !following) {
StartCoroutine (FollowPlayer ());
}
}
private IEnumerator FollowPlayer ()
{
following = true;
startTime = Time.time;
float fracComplete;
float dist;
do
{
fracComplete = (Time.time - startTime) / journeyTime;
dist = Vector3.Distance (Target.position, this.transform.position);
this.transform.position = Vector3.Lerp (this.transform.position, Target.position + distanceFromTarget, fracComplete);
yield return new WaitForEndOfFrame();
}
while (dist > 0.1f);
following = false;
}
}
But with this script my camera is always centered in the player, I don’t consider that the player can have a good perception of what is behind him when he is in the end of the grid and I guess I should change the camera distance from the player dynamically in some way, 'cause until now, when the player is in the first line of the grid he camera is too far from him.
Any suggestion so I could achieve this would be appreciated.
Thanks in advance.