Button 如何在屏幕宽度和高度范围内对Unity按钮进行简单的拖放
我是一名android开发人员,现在正在尝试使用unity。我试图用下面的代码在按钮上进行简单的拖放,但当我拖动到极限时,按钮就会丢失,我需要在屏幕宽度和高度范围内进行拖动,并且仅当我拖动按钮时进行。因此,我对Unity是新手,我需要您的指导。我从Unity论坛获得以下代码Button 如何在屏幕宽度和高度范围内对Unity按钮进行简单的拖放,button,drag-and-drop,unity3d,Button,Drag And Drop,Unity3d,我是一名android开发人员,现在正在尝试使用unity。我试图用下面的代码在按钮上进行简单的拖放,但当我拖动到极限时,按钮就会丢失,我需要在屏幕宽度和高度范围内进行拖动,并且仅当我拖动按钮时进行。因此,我对Unity是新手,我需要您的指导。我从Unity论坛获得以下代码 public class UserInterface : MonoBehaviour { public Rect playerPositionRect = new Rect(0, 151, 200, 50); private
public class UserInterface : MonoBehaviour {
public Rect playerPositionRect = new Rect(0, 151, 200, 50);
private Vector2 currentDrag = new Vector2();
void Start () {
}
void Update () {
}
void OnGUI(){
GUI.Box (playerPositionRect, "MyButton" );
Vector2 screenMousePosition = new Vector2(Input.mousePosition.x, Screen.height - Input.mousePosition.y);
if (currentDrag.sqrMagnitude != 0 || playerPositionRect.Contains(screenMousePosition)) {
if (Input.GetMouseButtonDown(0)) {
currentDrag = screenMousePosition;
} else if (Input.GetMouseButton(0)) {
playerPositionRect.x += (screenMousePosition.x - currentDrag.x);
playerPositionRect.y += (screenMousePosition.y - currentDrag.y);
currentDrag = screenMousePosition;
} else {
currentDrag.x = 0;
currentDrag.y = 0;
}
}
}
}
移动按钮后,您需要确保其仍在屏幕内。屏幕边缘是屏幕。宽度,屏幕。高度,0和0,如果它在外面,我们就把它移回去。当我们在屏幕的右侧和底部时,我们还需要调整按钮的高度和宽度
else if (Input.GetMouseButton(0)) {
playerPositionRect.x += (screenMousePosition.x - currentDrag.x);
playerPositionRect.y += (screenMousePosition.y - currentDrag.y);
playerPositionRect.x = Mathf.Clamp(playerPositionRect.x, 0, Screen.width - playerPositionRect.width);
playerPositionRect.y = Mathf.Clamp(playerPositionRect.y, 0, Screen.height - playerPositionRect.height);
currentDrag = screenMousePosition;
}
如果值超出范围,则Clamp只会剪切该值,因此,例如-5的x值将为0,或者10000000的值将为Screen.width-playerPositionRect.width