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!!
using UnityEngine;
using System.Collections;
public class ClickToMove : MonoBehaviour {
public float speed = 5;
Vector3 mousePos = new Vector3();
Quaternion rot = new Quaternion();
bool canMove = true;
void Update() {
if (Input.GetKeyDown(KeyCode.Mouse0)) {
if (Input.GetMouseButton (0) && canMove) {
mousePos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
//Debug.Log ("x : " + mousePos.x + " y : " + mousePos.y);
rot = Quaternion.LookRotation (transform.position - mousePos, Vector3.forward);
canMove = false;
}
}
if (!canMove) {
transform.position = Vector3.MoveTowards (transform.position, mousePos, speed * Time.deltaTime);
transform.rotation = rot;
transform.eulerAngles = new Vector3 (0, 0, transform.eulerAngles.z);
rigidbody2D.angularVelocity = 0;
//if(mousePos != null)
if(transform.position == mousePos)
canMove = true;
}
Debug.Log (transform.position);
}
}