I’m working at a horizontal 2d star shooter,and i need a way to make the player dont leave the camera(orthographic) bounds,in my game the camera moves automatic,with a scrolling background and some triggers parented,the enemy remain static in the scene and when the trigger touch then,they start doing what their supposed,but everything is a mess,i need a cleaner solution,like one big trigger that active everything it touch and destroy when the object leave it bounds and a way to make the player dont leave the current camera bounds
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
float playerRadiusBox = 0.5f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
// Restrict to cam boundry
Vector3 pos = transform.position;
if (pos.y + playerRadiusBox > Camera.main.orthographicSize) {
pos.y = Camera.main.orthographicSize - playerRadiusBox ;
}
if (pos.y - playerRadiusBox < -Camera.main.orthographicSize) {
pos.y = -Camera.main.orthographicSize + playerRadiusBox ;
}
float screenRatio = (float)Screen.width / (float)Screen.height;
float widthOrtho = Camera.main.orthographicSize * screenRatio;
if (pos.x + playerRadiusBox > widthOrtho) {
pos.x = widthOrtho - playerRadiusBox ;
}
if (pos.x - playerRadiusBox < -widthOrtho) {
pos.x = -widthOrtho + playerRadiusBox ;
}
transform.position = pos;
}
}
Add in your movement code to this script attach to player, it will keep the player in the camera bounds.