Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using UnityEngine;
- public class GetMousePos : MonoBehaviour
- {
- // the raw image that's rendering your game
- [SerializeField] private RectTransform rawImageRT;
- // the canvas that's rendering your raw image
- [SerializeField] private Canvas canvas;
- // the width/height of your render texture
- [SerializeField] private int renderWidth, renderHeight;
- private RectTransform _canvasRT;
- private float _canvasWidth, _canvasHeight, _scale, _rawImageBottomLeftX, _rawImageBottomLeftY;
- private Rect _canvasRect, _rtRect;
- // access the position through this variable
- [NonSerialized] public Vector3 pos;
- private void Awake()
- {
- _canvasRT = canvas.GetComponent<RectTransform>();
- }
- private void Update()
- {
- _canvasRect = _canvasRT.rect;
- _rtRect = rawImageRT.rect;
- _scale = renderWidth / _rtRect.width;
- _canvasWidth = _canvasRect.width * _scale;
- _canvasHeight = _canvasRect.height * _scale;
- _rawImageBottomLeftX = (_canvasWidth / 2.0f) - renderWidth - (_rtRect.xMin * _scale);
- _rawImageBottomLeftY = (_canvasHeight / 2.0f) - renderHeight - (_rtRect.yMin * _scale);
- pos = Input.mousePosition;
- pos.x = (pos.x / Screen.width * _canvasWidth) - _rawImageBottomLeftX;
- pos.y = (pos.y / Screen.height * _canvasHeight) - _rawImageBottomLeftY;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement