C# script to follow mouse cursor by GameObject.

 

Content not available.
Please allow cookies by clicking Accept on the banner

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
Tagged on:         

3 thoughts on “Unity 2D C# Follow Mouse Cursor

    • November 17, 2017 at 11:48 am
      Permalink

      I’ll try to do something with it 🙂

      Reply
  • November 18, 2017 at 1:48 pm
    Permalink

    Thanks for sharing 🙂

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. You can read more about it the Cookies&Privacy Policy Section Above. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this. You can read more about it the Cookies&Privacy Policy Section.

Close