- Home /
strange Rect behavior on Y axis
Hello there! My name is Niko. I have a little problem with my C# script.
using UnityEngine;
using System.Collections;
public class test : MonoBehaviour {
public float dynamicmouseX;
public float dynamicmouseY;
public float staticmouseX;
public float staticmouseY;
public bool Clicked = false;
public Texture gameStartTexture;
public void Update() {
dynamicmouseX = Input.mousePosition.x;
dynamicmouseY = Input.mousePosition.y;
}
public void OnMouseDown() {
staticmouseX = dynamicmouseX;
staticmouseY = dynamicmouseY;
if (Input.GetMouseButtonDown(0))
Clicked = true;
}
public void OnGUI() {
if (Clicked) {
GUI.DrawTexture (new Rect(staticmouseX,staticmouseY,100,100), gameStartTexture);
}
}
}
program should: 1) always calculate coordinates of the mouse position
public void Update() {
dynamicmouseX = Input.mousePosition.x;
dynamicmouseY = Input.mousePosition.y;
}
that's alright.
2) By mouse click, coordinates of the cursor must be written in variables "dynamicmouseX" and "dynamicmouseY"
public void OnMouseDown() {
staticmouseX = dynamicmouseX;
staticmouseY = dynamicmouseY;
if (Input.GetMouseButtonDown(0))
Clicked = true;
}
that's alright.
3) Also, by mouse click, program should draw texture in coordinates, which program has written
public void OnGUI() {
if (Clicked) {
GUI.DrawTexture (new Rect(staticmouseX,staticmouseY,100,100), gameStartTexture);
}
but, I have a problem with Y coordinates...
Why the rect is not displayed correctly on the Y axis? Known anybody alternative methods?
Answer by robertbu · Dec 12, 2013 at 07:38 PM
Input.mousePosition is in screen coordinates that start in the lower left corner of the screen. GUI coordinates start at the upper left of the screen. You can convert between the two by using:
float yGUI = Screen.height - yScreen;
Or in your case:
GUI.DrawTexture (new Rect(staticmouseX,Screen.height - staticmouseY,100,100), gameStartTexture);
While it cannot be done for every situation, the right way to code this behavior is to get the coordinates from the GUI Event and not make the conversion from Input.mousePosition:
Vector3 guiMousePosition = Event.current.mousePosition;
Hmm.. it is interesting. Thank you very much for your help! Your method works perfectly!
Your answer
Follow this Question
Related Questions
Problem with rect and touch 1 Answer
Multiple Cars not working 1 Answer
Wraping text to fit in a gui box 1 Answer
Can't destroy an ui element 2 Answers
GUI label dimensions bug 2 Answers