- Home /
Mouse cursor position relative to the object
I can not figure out the way to calculate how the mouse cursor corresponds with the object center in 2D sceen plane. To be more clear, I need to calculate if the cursor is more to the left or to the right relatively to the center of the object.
Answer by Positive7 · Jul 28, 2015 at 03:31 PM
using UnityEngine;
public class test3 : MonoBehaviour
{
void Update(){
Vector2 mouse = new Vector2(Input.mousePosition.x,Input.mousePosition.y);
Ray ray;
ray = Camera.main.ScreenPointToRay(mouse);
RaycastHit hit;
if(Physics.Raycast(ray,out hit, 10))
{
if(hit.point.x < transform.position.x)
Debug.Log("Left");
else
Debug.Log("Right");
}
}
}
Something like this should work on UI :
private void Update()
{
var pointer = new PointerEventData(EventSystem.current) { position = Input.mousePosition };
var raycastResults = new List<RaycastResult>();
EventSystem.current.RaycastAll(pointer, raycastResults);
if (raycastResults.Count > 0)
{
foreach (var raycastResult in raycastResults)
{
if (EventSystem.current.IsPointerOverGameObject() && raycastResult.gameObject.name == "Button")
{
Debug.Log(Input.mousePosition.x < raycastResult.gameObject.transform.position.x ? raycastResult.gameObject.name + " Left" : raycastResult.gameObject.name + " Right");
}
}
}
}
$$anonymous$$aybe there is a more efficient way tho.
Good idea, but it turns out RectTransformUtility
is the way to go.
Answer by lightgem12 · Oct 18, 2015 at 09:13 AM
Well, this is what I did to find the distance between them for x and y:
public Camera camera;
public Transform obj;
Vector2 objPos;
Vector2 mousePos;
float mousePosY, mousePosX;
void Update ()
{
objPos = obj.transform.position;//gets player position
mousePos = Input.mousePosition;//gets mouse postion
mousePos = camera.ScreenToWorldPoint (mousePos);
mousePosX = mousePos.x - objPos.x;//gets the distance between object and mouse position for x
mousePosY = mousePos.y - objPos.y;//gets the distance between object and mouse position for y if you want this.
}
you wont need the y for this situation, but I thought I might as well show that too. I'm not going to tell you how to implement it into an if statement, I'm sure you can handle it. Hope this helps, and works.
Your answer
Follow this Question
Related Questions
Mouse cursor texture change 0 Answers
using mouse cursor to change levels 0 Answers
mouse shape not ok 0 Answers
Mouse cursor problem exporting in windows store 0 Answers
Mouse Coursor hide/show 1 Answer