C# script to follow mouse cursor by GameObject.
using System.Collections; using System.Collections.Generic; using UnityEngine; // ? 2017 TheFlyingKeyboard and released under MIT License // theflyingkeyboard.net public class FollowMouse : MonoBehaviour { public float moveSpeed = 0.004f; // Use this for initialization void Start () { } // Update is called once per frame void Update () { transform.position = Vector2.Lerp(transform.position, Camera.main.ScreenToWorldPoint(Input.mousePosition), moveSpeed); Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position; difference.Normalize(); float rotation_z = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg; transform.rotation = Quaternion.Euler(0f, 0f, rotation_z); } }
Unity 2D C# Follow Mouse Cursor
Great post. Any thoughts on turning this into a “go to click” location with a smooth turn and forward movement? Like the graphic in this unity question: https://answers.unity.com/questions/763139/rotate-while-moving-forward.html
Would be great to see a code sample that does what that graphic does, but with only one waypoint, the mouse click location.
I’ll try to do something with it 🙂
Thanks for sharing 🙂