Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Mouse position registering in corner of screen with new input system.

Discussion in 'Input System' started by a_root, Jan 22, 2021.

  1. a_root

    a_root

    Joined:
    Sep 19, 2017
    Posts:
    1
    So I am working on a game and I would like to make a gun that follows my mouse. I am using the new input system and It should be pretty easy. But after a couple of days of testing I have decided to ask for help. My problem is that the mouse point that the gun should be pointing at is in the corner of the screen and not in the center. If you need more clarification I can upload videos.
    Code (CSharp):
    1. Vector2 pos = playerCamera.ScreenToViewportPoint(Mouse.current.position.ReadValue());
    2. transform.up = pos;
     
  2. XianGrim

    XianGrim

    Joined:
    Jan 14, 2014
    Posts:
    7
    If anyone else comes across this post, I had the same issue. Here was my fix for it:

    Code (CSharp):
    1.     public class FollowMouseForUI : MonoBehaviour
    2.     {
    3.         [SerializeField] Canvas myCanvas;
    4.         private Camera cam;
    5.         private Vector2 mousePosition;
    6.         private Vector2 pos;
    7.  
    8.         private void Awake()
    9.         {
    10.             cam = Camera.main;
    11.         }
    12.  
    13.         // Update is called once per frame
    14.         void Update()
    15.         {
    16.             RectTransformUtility.ScreenPointToLocalPointInRectangle(myCanvas.transform as RectTransform, Mouse.current.position.ReadValue(), myCanvas.worldCamera, out pos);
    17.             transform.position = myCanvas.transform.TransformPoint(pos);
    18.         }
    19.     }
     
    mikawendt likes this.