Transform.position not working- want to clamp object within confines of screen
Hi!
I have an object that I can move around my screen (canvas) using the below script. I have added in a bit of code to try and stop the object from disappearing off the screen if I move it too far on the x or y axes- the max and min values for this are 40 and -40 for x and y. However, when I play the scene I can still move the object way off on the x or y so it's no longer within the scene... Any ideas why this code isn't working? Thanks!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Panning : MonoBehaviour
{
public Vector3 boundsMax;
public Vector3 boundsMin;
DragMouseOrbit dmo;
void Start() {
dmo = Camera.main.GetComponent<DragMouseOrbit> ();
}
void Update() {
transform.position = new Vector3 (Mathf.Clamp (transform.position.x, boundsMin.x, boundsMax.x), Mathf.Clamp (transform.position.y, boundsMin.y, boundsMax.y), Mathf.Clamp (transform.position.z, boundsMin.z, boundsMax.z));
}
void LateUpdate()
{
if (Input.touchCount > 2 || Input.GetMouseButton (2)) {
Vector3 mousePosition = new Vector3 (Input.mousePosition.x, Input.mousePosition.y, dmo.distance);
/// Debug.Log (mousePosition);
Vector3 objPosition = Camera.main.ScreenToWorldPoint (mousePosition);
transform.position = objPosition;
} else {
transform.position = Vector3.zero;
}
}
}
Comment