- Home /
Question by
UserNobody · Oct 03, 2019 at 01:31 PM ·
editorwindowmousepositioncoordinatespixel
How to get pixel coordinates from mouse position?
Hello everyone!
I am making an editor extension that will allow me to paint textures within editor, but I have trouble getting a pixel coordinates from a mouse click position.
I know there's some math involved, but I'm terrible at math unfortunately.. So not sure how to achieve this :/ Is there some Unity's helper method that I could use maybe? Or if there are none, what calculation is needed to get the pixel coordinates?
I would really appreciate any help! Thank you!
This is my code:
using System;
using UnityEditor;
using UnityEngine;
public class Painting : EditorWindow
{
int size = 5;
float zoomScale = 1.0f;
Rect imgRect
{
get
{
return new Rect(25, 25, this.position.width - 50, this.position.height - 50);
}
}
Texture2D texture = null;
[MenuItem("Painter/Open")]
public static void OpenWindow()
{
var window = EditorWindow.GetWindow<Painting>("Painter");
window.Show();
}
private void OnEnable()
{
this.Setup();
}
private void Setup()
{
texture = new Texture2D(Screen.width, Screen.height);
Color32[] pixels = new Color32[texture.width * texture.height];
for (int i = 0; i < pixels.Length; i++)
{
pixels[i] = new Color32(255, 255, 255, 255);
}
texture.SetPixels32(pixels);
texture.Apply();
}
private void OnGUI()
{
Matrix4x4 oldMatrix = GUI.matrix;
BeginWindows();
Matrix4x4 Translation = Matrix4x4.TRS(new Vector3(Screen.width / 2, Screen.height / 2, 0), Quaternion.identity, Vector3.one);
Matrix4x4 Scale = Matrix4x4.Scale(new Vector3(zoomScale, zoomScale, 1.0f));
GUI.matrix = Translation * Scale * Translation.inverse;
GUIStyle imageStyle = new GUIStyle(); imageStyle.normal.background = texture;
GUI.Label(imgRect, GUIContent.none, imageStyle);
GUI.BeginGroup(imgRect);
GUI.matrix = oldMatrix;
var e = Event.current;
if (e.type == EventType.MouseDown && e.button == 0)
{
this.Paint(GUIUtility.ScreenToGUIPoint(e.mousePosition));
}
else if (e.type == EventType.ScrollWheel)
{
var zoomDelta = 0.1f;
zoomDelta = e.delta.y < 0 ? zoomDelta : -zoomDelta;
zoomScale += zoomDelta;
zoomScale = Mathf.Clamp(zoomScale, 0.25f, 1.25f);
e.Use();
}
GUI.EndGroup();
}
private void Paint(Vector2 point)
{
Debug.Log(point);
for (int x = Convert.ToInt32(point.x) - size; x < Convert.ToInt32(point.x) + size; x++)
{
for (int y = Convert.ToInt32(point.y) - size; y < Convert.ToInt32(point.y) + size; y++)
{
texture.SetPixel(x, y, new Color32(0, 0, 0, 1));
}
}
texture.Apply();
this.Repaint();
}
}
Comment