- Home /
Question by
Zoogyburger · Feb 21, 2016 at 05:31 AM ·
boundsbox collider2d camera
Camera in changing scenes automatically assign a boxcollider in the Inspecter.
I have a Gameobject with a boxcollider2D on it and Camera with the following code on it:
using UnityEngine;
using System.Collections;
public class FollowCamera : MonoBehaviour {
public Transform Player;
private static bool CamExists;
public Vector2
Margin,
Smoothing;
public BoxCollider2D Bounds;
private Vector3
_min,
_max;
public bool IsFollowing { get; set; }
public void Start()
{
_min = Bounds.bounds.min;
_max = Bounds.bounds.max;
IsFollowing = true;
if (!CamExists) {
CamExists = true;
DontDestroyOnLoad (transform.gameObject);
} else {
Destroy (gameObject);
}
}
public void Update()
{
var x = transform.position.x;
var y = transform.position.y;
if (IsFollowing)
{
if (Mathf.Abs(x = Player.position.x) > Margin.x)
x = Mathf.Lerp (x, Player.position.x, Smoothing.x * Time.deltaTime);
if (Mathf.Abs(y = Player.position.y) > Margin.y)
y = Mathf.Lerp(y, Player.position.x, Smoothing.y * Time.deltaTime);
}
var cameraHalfWidth = GetComponent<Camera>().orthographicSize * ((float)Screen.width / Screen.height);?
x = Mathf.Clamp(x, _min.x + cameraHalfWidth, _max.x - cameraHalfWidth);
y = Mathf.Clamp(y, _min.y + GetComponent<Camera>().orthographicSize, _max.y - GetComponent<Camera>().orthographicSize);
transform.position = new Vector3 (x, y, -10);
}
}
My BoxCollider2D tells the Camera when to stop. But the shape of it must change from scene to scene. How do I set the public BoxCollider2D to be the right shape in runtime? Thanks
Comment
Best Answer
Answer by Zoogyburger · Feb 21, 2016 at 08:18 PM
Sorry, I fixed the problem myself. Instead of writing this:
if (!CamExists) {
CamExists = true;
DontDestroyOnLoad (transform.gameObject);
} else {
Destroy (gameObject);
}
I have it so the Camera finds the player in every different scene:
Player = GameObject.FindWithTag ("Player").transform;