I’m starting on a simple 2D game where I have several scenes of random tilesets, and I’m trying to make one nice script that takes the boundaries of the tileset, then follows the player until it gets to a border of the tileset. At this point I want it to stop moving the camera to that border, but allow the player to move up to the border without showing the outside of my tilemap. I tried something like this in the code, but it refuses to follow the player unless I get rid of the second update for the transform.position
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
public class testScript : MonoBehaviour
{
public Transform target;
public Tilemap tilemap;
private Vector3 bottomLeftLimit;
private Vector3 topRightLimit;
private float halfHeight;
private float halfWidth;
// Start is called before the first frame update
void Start()
{
target = FindObjectOfType<PlayerMover>().transform;
halfHeight = Camera.main.orthographicSize;
halfWidth = halfHeight * Camera.main.aspect;
bottomLeftLimit = tilemap.localBounds.min + new Vector3(halfWidth, halfHeight, 0f);
topRightLimit = tilemap.localBounds.max + new Vector3(-halfWidth, -halfHeight, 0f);
}
// Update is called once per frame
void Update()
{
transform.position = new Vector3(target.position.x, target.position.y, transform.position.z);
transform.position = new Vector3(Mathf.Clamp(target.transform.position.x, bottomLeftLimit.x, topRightLimit.x), Mathf.Clamp(target.transform.position.y, bottomLeftLimit.y, topRightLimit.y), transform.position.z);
}
}