Advertisement
Guest User

Unity Convert Mouse Position

a guest
Aug 6th, 2019
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.44 KB | None | 0 0
  1. using System;
  2. using UnityEngine;
  3.  
  4. public class GetMousePos : MonoBehaviour
  5. {
  6.     // the raw image that's rendering your game
  7.     [SerializeField] private RectTransform rawImageRT;
  8.  
  9.     // the canvas that's rendering your raw image
  10.     [SerializeField] private Canvas canvas;
  11.    
  12.     // the width/height of your render texture
  13.     [SerializeField] private int renderWidth, renderHeight;
  14.  
  15.     private RectTransform _canvasRT;
  16.    
  17.     private float _canvasWidth, _canvasHeight, _scale, _rawImageBottomLeftX, _rawImageBottomLeftY;
  18.  
  19.     private Rect _canvasRect, _rtRect;
  20.  
  21.     // access the position through this variable
  22.     [NonSerialized] public Vector3 pos;
  23.  
  24.     private void Awake()
  25.     {
  26.         _canvasRT = canvas.GetComponent<RectTransform>();
  27.     }
  28.  
  29.     private void Update()
  30.     {
  31.         _canvasRect = _canvasRT.rect;
  32.         _rtRect = rawImageRT.rect;
  33.        
  34.         _scale = renderWidth / _rtRect.width;
  35.        
  36.         _canvasWidth = _canvasRect.width * _scale;
  37.         _canvasHeight = _canvasRect.height * _scale;
  38.        
  39.  
  40.         _rawImageBottomLeftX = (_canvasWidth / 2.0f) - renderWidth - (_rtRect.xMin * _scale);
  41.         _rawImageBottomLeftY = (_canvasHeight / 2.0f) - renderHeight - (_rtRect.yMin * _scale);
  42.  
  43.        
  44.         pos = Input.mousePosition;
  45.         pos.x = (pos.x / Screen.width * _canvasWidth) - _rawImageBottomLeftX;
  46.         pos.y = (pos.y / Screen.height * _canvasHeight) - _rawImageBottomLeftY;
  47.     }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement