I am using x and z axis to go left/right ; up/down respectively. The Camera is on the y-axis.
I have the following code so far -
private float playerWidth; private float playerDepth;
private Vector2 screenBounds;
// Other Variables and Initiators
// Start is called before the first frame update
void Start()
{
playerRigidbody = GetComponent<Rigidbody>();
screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z));
//gives x and y values that will be half the screen value. Screen coordinate system is reversed, so these will be negative values
playerWidth = transform.GetComponent<BoxCollider>().bounds.size.x / 2;
playerDepth = transform.GetComponent<BoxCollider>().bounds.size.z / 2;
// we need half the size as we already are at the center of the object, using clamp
}
Tutorials are using SpriteRenderer as this would make more sense in a 2D game, however I am working in 3D space, creating a 2.5D effect.
private void LateUpdate()
{
withinScreenBounds();
}
private void withinScreenBounds()
{
// check if player does not exceed camera view, else stop all movement.
Vector3 viewPos = transform.position;
viewPos.x = Mathf.Clamp(viewPos.x, screenBounds.x + playerWidth, screenBounds.x * -1 - playerWidth);
viewPos.z = Mathf.Clamp(viewPos.z, screenBounds.y + playerDepth, screenBounds.y * -1 - playerDepth);
transform.position = viewPos;
// the above will work with the center of the tank.
}
The tank is currently jittering between screenpoints, not sure if this has to do with the boxcollider itself.