Hello, I am trying to limit player movement to screen borders! The object is following players mouse movement. Problem is how can I limit where can the player go. I want the player to have a possibility to go outside of the screen, then vector 3 will be limited by that border, but player can still move on that border. for example: Player moves too much to the right. It stops his further movement to the right, but player can still go up and down, if he is between .y borders. Also, another problem is that coordinates (0, 0, z) place the border on the middle of the screen instead of bottomleft corner. Code and images below:
Thank you for your time.
public class PlayerMove : MonoBehaviour {
private Vector3 mousePosition;
public float moveSpeed = 0.9f;
public float angle = 120;
double screenX = Screen.width - 1;
double screenY = Screen.height - 1;
Vector3 bottomleft = new Vector3(0, 0, -1);
// Use this for initialization
void Start () {
Cursor.visible = false;
}
// Update is called once per frame
void Update () {
mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.Rotate(0, 0, -angle * Time.deltaTime);
if (mousePosition.x <= 0 && mousePosition.y <= 0)
{
transform.position = Vector3.Lerp(new Vector3(transform.position.x, transform.position.y, -1), new Vector3(0, 0, -1), moveSpeed);
}
else if(mousePosition.x >= Screen.width -1 && mousePosition.y >= Screen.height -1)
{
transform.position = Vector3.Lerp(new Vector3(transform.position.x, transform.position.y, -1), new Vector3(Screen.width, Screen.height, -1), moveSpeed);
}
else if (mousePosition.x <= 0)
{
transform.position = Vector3.Lerp(new Vector3(transform.position.x, transform.position.y, -1), new Vector3(0, mousePosition.y, -1), moveSpeed);
}
else if (mousePosition.x >= Screen.width/4)
{
transform.position = Vector3.Lerp(new Vector3(transform.position.x, transform.position.y, -1), new Vector3(Screen.width - 1, mousePosition.y, -1), moveSpeed);
}
else if (mousePosition.y <= 0)
{
transform.position = Vector3.Lerp(new Vector3(transform.position.x, transform.position.y, -1), new Vector3(mousePosition.x, 0, -1), moveSpeed);
}
else if (mousePosition.y >= Screen.height/4)
{
transform.position = Vector3.Lerp(new Vector3(transform.position.x, transform.position.y, -1), new Vector3(mousePosition.x, Screen.height, -1), moveSpeed);
}
else
{
transform.position = Vector3.Lerp(new Vector3(transform.position.x, transform.position.y, -1), new Vector3(mousePosition.x, mousePosition.y, -1), moveSpeed);
}
}
}