Search Unity

Unity 2D: Object moves only in Z axis.

Discussion in 'Scripting' started by Ziya, Nov 5, 2016.

  1. Ziya

    Ziya

    Joined:
    Aug 30, 2013
    Posts:
    65
    I want to move an object by mouse. The object moves only in Z axis. It doesn't move in X and Y, they don't change. I need it to move in X and Y too.

    I did next.
    1. Added a cube.
    2. Added the next script to the cube:
    Code (CSharp):
    1.     void Start () {
    2.  
    3.     }
    4.  
    5.     // Update is called once per frame
    6.     public Vector3 targetPosition;
    7.  
    8.     // Update is called once per frame
    9.     void Update()
    10.     {
    11.         if (Input.GetKeyDown(KeyCode.Mouse0))
    12.         {
    13.             targetPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    14.             targetPosition.z += 10;
    15.         }
    16.  
    17.         transform.position = Vector3.MoveTowards(transform.position, targetPosition, Time.deltaTime * 5);
    18.     }
    3. Switched to 2D.
    4. Run the game.
     
    Last edited: Nov 5, 2016
  2. Ziya

    Ziya

    Joined:
    Aug 30, 2013
    Posts:
    65
    The problem was when I created a 3D project and then switched to 2D. It didn't work.
    But when I created a new 2D project, it worked.
     
    Last edited: Nov 5, 2016