- Home /
Make object follow mouse cursor in 2D
I'm makin a game in Unity 2D, and need an object to follow the mouse movement in order to make a custom and changeable cursor. This is the code I have currently. At the moment, it follows the mouse, but is displaced from the mouse about of of the screen to the top left, i.e. if the mouse is at the bottom left of the screen, the cursor is in the middle.
Current Code:
using UnityEngine;
using System.Collections;
public class Cursor : MonoBehaviour {
// Use this for initialization
void Start () {
Screen.showCursor = false;
}
// Update is called once per frame
void Update () {
Vector3 mouse = Input.mousePosition;
mouse = mouse * 10F;
transform.position = Camera.main.ScreenToViewportPoint(mouse);
}
}
Answer by fafase · Nov 15, 2013 at 07:37 PM
mouse = mouse * 10F;
why is that for? If your mouse is at (10,10) then you get at (100,100) then the conversion goes also wrong.
We added that because the cursor we made wasn't following at the same speed as the mouse input. Before we put that in, the cursor moved at 1/10 the rate of the mouse.
The cursor to be slower is to be expected. I think it is due to how mouse event and guiTexture are handled. Have you tried to use the payer settings: http://docs.unity3d.com/Documentation/$$anonymous$$anual/class-PlayerSettings.html ?