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.

  1. 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.

  1. 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?

1 Answer

1

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!