How to make a game object follow the camera but with it's position

 


There is the steps of making the GameObject following the camera but with its initial position

1- Create an empty gameobject by right click in the hierarchy then create empty gameobject.
2- Add your sprite to that gameobject.
3- Click on the add Component then add new script 

using UnityEngine;

public class FollowCamera : MonoBehaviour
{
    private Transform mainCameraTransform;
    private Vector3 initialSunOffset;

    void Start()
    {
        mainCameraTransform = Camera.main.transform;
        initialSunOffset = transform.position - mainCameraTransform.position; // Calculate the initial offset between sun and camera
    }

    void LateUpdate()
    {
        // Update the position of the sun relative to the camera's movement
        transform.position = mainCameraTransform.position + initialSunOffset;
    }
}


4-Test the result on the scene of game in unity editor.



Happy coding



Previous Post Next Post

Contact Form