- Home /
2D how to make a sprite follow the mouse position #c
I've started programming with Unity not long ago and I have a noob question:
The sprite should follow the mouse and should have the same position all the time. When I first try writing the code I came across a little problem: The sprite moves outside the camera area, although the mouse is inside.
In the game I'm programming the mouse should be able to drag an drop object from one point to another. Simiar to a dress-up game.
Thanks for reading.
This is my code:
using UnityEngine; using System.Collections;
public class followTheMouse : MonoBehaviour {
Rigidbody2D rigid;
// Use this for initialization
void Start () {
rigid = GetComponent<Rigidbody2D> ();
}
// Update is called once per frame void Update () {
float mouseX = Input.mousePosition.x;
float mouseY = Input.mousePosition.y;
Vector2 followthecursor = new Vector2 (mouseX, mouseY);
rigid.MovePosition ((Vector2)transform.position +(Vector2)followthecursor);
}
}
Answer by crohr · Jun 11, 2015 at 04:49 PM
You will want to use Camera.ScreenToWorldPoint to convert the mouse position to world coordinates. http://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html
No problem, good luck! Don't forget to accept this answer for future readers.
Hey, i'm trying to make a similar script, but am having no luck. Can you post the full script?
$$anonymous$$eep in $$anonymous$$d to reset the Z position to 0. Sometimes it changes to 10 or so.
Answer by lqvinh2 · Nov 29, 2018 at 09:31 AM
void Update () { // for 2D game Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition); mousePos .z = 0; speed = 150; transform.position = Vector3.Lerp(transform.position, mousePos , speed * Time.deltaTime); }