So I been currently trying to restrict the player’s movement dynamically without hard coding any values.
As of now, this how my player controller class looks like.
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public const float MAX_SPEED = 5.0f;
// Update is called once per frame
void Update()
{
transform.Translate(Input.GetAxis("Horizontal") * MAX_SPEED * Time.deltaTime, 0.0f, 0.0f);
clampPlayersMovementX();
}
void clampPlayersMovementX()
{
Vector3 pos = Camera.main.WorldToViewportPoint(transform.position);
pos.x = Mathf.Clamp01(pos.x);
transform.position = Camera.main.ViewportToWorldPoint(pos);
}
}
After a reading a couple of posts in the unity forums, the general consensus is to use Mathf.clamp but the problem is that my clampPlayersMovementX function still lets half of the players body go through the screen and the reason why is because the object’s pivot is at the center. So I’ve tried to use bound.center.x property in the sprite renderer component to see if it would completely stop the player from going off the screen but it did not help. Any ideas?
If you want to support sprites with non-center pivots you can do:
//Units on the left from the sprite's pivot.
float xLeft= sprite.pivot.x / sprite.pixelsPerUnit;
//Units on the right from the sprite's pivot.
float xRight = (sprite.texture.width - sprite.pivot.x) / sprite.pixelsPerUnit;
Then you have to check two x values instead of one in the clampPlayersMovementX method:
Vector3 posMin = transform.position; //Sprite's left bound.
Vector3 posMax = transform.position; //Sprite's right bound.
posMin.x = posMin.x - xLeft;
posMax.x = posMax.x + xRight;
//Check if posMin.X and posMax.x are in the viewport.