I’m trying to make sure my player doesn’t go out of the screen using code but for some reason only the upper and right part of the screen has boundaries. Here’s my code and a screenshot highlighting the parts that have boundaries.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour {
public Vector2 speed;
private Rigidbody2D rb2d;
private float ScreenHalfSize;
void Start () {
rb2d = GetComponent<Rigidbody2D> ();
ScreenHalfSize = Camera.main.aspect * Camera.main.orthographicSize;
}
void FixedUpdate () {
Vector2 velocity;
velocity.x = Input.GetAxis ("Horizontal") * speed.x * Time.deltaTime;
velocity.y = Input.GetAxis ("Vertical") * speed.y * Time.deltaTime;
transform.Translate (velocity);
if (transform.position.x <= -ScreenHalfSize) {
Debug.Log("x <= -ScreenHalfSize");
transform.Translate (new Vector2 (velocity.x, 0));
}
else if (transform.position.x >= ScreenHalfSize) {
Debug.Log("x >= ScreenHalfSize");
transform.Translate (new Vector2 (-velocity.x, 0));
}
if (transform.position.y <= -Camera.main.orthographicSize) {
Debug.Log("y <= -ScreenHalfSize");
transform.Translate (new Vector2 (0, velocity.y));
}
else if (transform.position.y >= Camera.main.orthographicSize) {
Debug.Log("y >= ScreenHalfSize");
transform.Translate (new Vector2 (0, -velocity.y));
}
}
}