- Home /
Restraining movement to camera bounds
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
Answer by test45 · Jul 15, 2018 at 05:08 AM
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.
Your answer
Follow this Question
Related Questions
enter a trigger to access other camera? 1 Answer
Active camera on Start 1 Answer
How to trigger with camera? 2 Answers
Keep Cursor In Bounds of Camera 2 Answers
Capture Bounds with an orthographic camera -- runtime world map 1 Answer