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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Object following player when left mouse button is down

Discussion in 'Scripting' started by unity_nVdYtceNQmOPDw, Jun 12, 2018.

  1. unity_nVdYtceNQmOPDw

    unity_nVdYtceNQmOPDw

    Joined:
    Jun 12, 2018
    Posts:
    15
    Hi,i would like to do a 2d game where if you hold down the left mouse button the object would follow the mouse if you move it,but every time i do this the object dissappears: if(Input.getMouseButtonDown(0)) {
    transform.position = Input.MousePosition;
    }
     
  2. bakir-omarov

    bakir-omarov

    Joined:
    Aug 1, 2015
    Posts:
    48
    Are you making 3D game or 2D ?
     
  3. unity_nVdYtceNQmOPDw

    unity_nVdYtceNQmOPDw

    Joined:
    Jun 12, 2018
    Posts:
    15
    I'd like to make a 2d game.
     
  4. bakir-omarov

    bakir-omarov

    Joined:
    Aug 1, 2015
    Posts:
    48
    This script will do what you want, but my advice go to Unity Learn, and watch all tutorials here, then watch more and more videos on youtube. Because it will be hard to continue without knowledge.

    Script (must be attached to follower GameObject in Unity 2D):
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Movement : MonoBehaviour
    6. {
    7.     public float movementSpeed = 2.0f;
    8.  
    9.     void Update()
    10.     {
    11.         // checking if mouse was pressed down, if yes then implement the script
    12.         if (Input.GetKey(KeyCode.Mouse0))
    13.         {
    14.             // getting mouse position in world coordinate system
    15.             Vector2 mouseVector2 = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    16.             // changing Object position by -Vector2.MoveTowards- function. Control speed by float -movementSpeed-
    17.             transform.position = Vector2.MoveTowards(transform.position, mouseVector2, movementSpeed * Time.deltaTime);
    18.         }
    19.     }
    20. }
    21.  
     
  5. unity_nVdYtceNQmOPDw

    unity_nVdYtceNQmOPDw

    Joined:
    Jun 12, 2018
    Posts:
    15
    Thank you!I will watch the videos, i use to watch Brackeys but i can't write my own codes yet.
     
  6. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712