#Changing mouse events position
1 messages · Page 1 of 1 (latest)
if you click with the real mouse, call the fake mouse's event, that isn't difficult at all
I did try it and i can trigger any event from my custom components pretty well. But for Unity's components (like Scrollbar, InputField, etc..), they still use the real mouse.
Ok, there might be a simpler solution by utilizing something left by Unity, but my solution would be to inherit the UI components into custom ones and change their behavior to react to your fake mouse.
Here is a simple Fake mouse component:
public class FakeMouse : MonoBehaviour
{
public delegate void PressedEvent(Vector2 position);
public PressedEvent pressed;
[HideInInspector] public RectTransform rectTransform;
private void Awake()
{
rectTransform = GetComponent<RectTransform>();
}
private void Update()
{
if (Input.GetMouseButton(0))
{
pressed?.Invoke(rectTransform.rect.center);
}
}
}
And here is the rest:
public class CustomButton : Button
{
private FakeMouse fakeMouse;
protected override void Start()
{
base.Start();
fakeMouse = FindObjectOfType<FakeMouse>();
fakeMouse.pressed += FakeMousePressed;
}
private void FakeMousePressed(Vector2 position)
{
if (fakeMouse.rectTransform.DoesOverlapWith(GetComponent<RectTransform>())) onClick?.Invoke();
}
}
public static class CustomUIElementUtility
{
public static bool DoesOverlapWith(this RectTransform rectTransformOrigin, RectTransform rectTransformOther)
{
Rect rectOther = rectTransformOther.rect, rectOrigin = rectTransformOrigin.rect;
return (rectTransformOrigin.localPosition.x < rectTransformOther.localPosition.x + rectOther.width &&
rectTransformOrigin.localPosition.x + rectOrigin.width > rectTransformOther.localPosition.x &&
rectTransformOrigin.localPosition.y < rectTransformOther.localPosition.y + rectOther.height &&
rectTransformOrigin.localPosition.y + rectOrigin.height > rectTransformOther.localPosition.y);
}
}
Now I think it's quite self explanatory what I did there, the FakeMouse component is supposed to be on an Image component in the UI because of the handy rectTransform component, but with some adjustments you could probably make it work in World Space too, perhaps using bounds or raycasts or something.
Then I take the built in Button component, add the FakeMousePressed() method to the FakeMouse's pressed event and in it, if the FakeMouse's Rect overlaps my custom button's rect, call the button's onClick event.
Dont forget to use the CustomButton instead of the basic Button in the UI