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
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Need help, Vector3.MoveTowards GameObject disappears after moving...

Discussion in 'Scripting' started by Kid_Niki, Sep 6, 2014.

  1. Kid_Niki

    Kid_Niki

    Joined:
    Feb 4, 2014
    Posts:
    5
    Okay, I'm totally baffled but new to this so I'm probably missing something. My code works, I'm not sure if it is the most efficient but it works, well sort of. The problem is that when the game object gets to where it is supposed to go, it disappears! I have a Debug to check the current position of the gameObject and it continues to move when I click but it isn't visible. Can anyone help with this? Thank you!!

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class ClickToMove : MonoBehaviour {
    5.  
    6.  
    7.  
    8.     public float speed = 5;
    9.     Vector3 mousePos = new Vector3();
    10.     Quaternion rot = new Quaternion();
    11.     bool canMove = true;
    12.  
    13.     void Update() {
    14.  
    15.  
    16.        
    17.         if (Input.GetKeyDown(KeyCode.Mouse0)) {
    18.         if (Input.GetMouseButton (0) && canMove) {
    19.             mousePos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
    20.             //Debug.Log ("x : " + mousePos.x + " y : " + mousePos.y);
    21.             rot = Quaternion.LookRotation (transform.position - mousePos, Vector3.forward);
    22.             canMove = false;  
    23.  
    24.         }
    25.         }
    26.         if (!canMove) {
    27.                         transform.position = Vector3.MoveTowards (transform.position, mousePos, speed * Time.deltaTime);
    28.                         transform.rotation = rot;
    29.                         transform.eulerAngles = new Vector3 (0, 0, transform.eulerAngles.z);
    30.                         rigidbody2D.angularVelocity = 0;
    31.                         //if(mousePos != null)
    32.                         if(transform.position == mousePos)
    33.                         canMove = true;
    34.                 }
    35.         Debug.Log (transform.position);
    36.     }
    37. }
    38.  
     
  2. Kid_Niki

    Kid_Niki

    Joined:
    Feb 4, 2014
    Posts:
    5
    Forget it, I see the Z is changing and it is moving behind the camera! o_O
     
  3. takito

    takito

    Joined:
    Apr 15, 2013
    Posts:
    11
    Can you please post how you fixed this problem? Thanks