- Home /
Camera follow player with procedural generation
Hello i wonder how can i implement camera what follows player in my game. Situation is following - first level is generated - then player is instantiated somewhere in this level then i want camera to follow player to do so - camera needs to have a target that it will follow.. but when game starts camera can not locate player - because level is still generating... so u cant implement click to move mechanic with camera cos camera has no target... what is the best way to make it work? assuming its a 3d top down game where player movement is depend on camera cos its a click to move movement scheme..
Answer by Master109 · Feb 23 at 04:14 AM
While the level is generating and the player does not exist yet, you can move the camera like:
using System;
using UnityEngine;
public class CameraScript : MonoBehaviour
{
[SerializeField] Transform trs;
[SerializeField] Camera camera;
[SerializeField] float moveSpeed;
Plane groundPlane;
Vector3 moveTo;
void Start ()
{
groundPlane = new Plane(Vector3.up, 0);
moveTo = trs.position;
}
void Update ()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = camera.ScreenPointToRay(Input.mousePosition);
float hitDistance;
if (groundPlane.Raycast(ray, out hitDistance))
{
moveTo = ray.GetPoint(hitDistance);
moveTo.y = trs.position.y;
}
else
throw new Exception("The camera is not directly facing the ground");
}
trs.position += Vector3.ClampMagnitude(moveTo - trs.position, moveSpeed * Time.deltaTime);
}
}
Answer by itcahi801 · Feb 23 at 10:07 AM
im not sure to much but I usually use cinema machine i would highly recomend it there are lots of tutorials on youtube for it all you have to do is download it add it to your scene then add the player to the follow part
Answer by Kosmik123 · Feb 23 at 11:42 PM
Why don't you instantiate camera object with player at the same time? Until level is loaded: there will be no player and no camera, and then when everything loads: player and his camera are created