When the player clicks, I am trying to use a RayCast to find the point that the player is looking at, and then instantiate a sphere object. I then try to use MoveTowards() to try to make the sphere move towards the point that the player is looking at. For some reason, when I run my game, clicking spawns spheres, but they don't move at all from their starting position.
Here is my code:
public class SphereBehaviour : MonoBehaviour {
public Transform player;
public GameObject spherePrefab;
private float leftRight = 0;
private Vector3 target;
private GameObject sphereInstance;
void Start () {
}
void Update () {
if(Input.GetMouseButtonDown(0)){
Camera camera = player.GetComponent<Camera> ();
RaycastHit hit;
if (Physics.Raycast (player.transform.position, camera.transform.forward, out hit)) {
target = hit.point;
} else {
target = player.transform.forward;
}
//Alternates between spawning the sphere to the left and right of the player
if (leftRight == 0) {
sphereInstance = Instantiate (spherePrefab, (player.TransformPoint (new Vector3 (1, -.5f, -2))), Quaternion.identity) as GameObject;
leftRight = 1;
} else {
sphereInstance = Instantiate (spherePrefab, (player.TransformPoint (new Vector3 (-1, -.5f, -2))), Quaternion.identity) as GameObject;
leftRight = 0;
}
sphereInstance.transform.position = Vector3.MoveTowards(sphereInstance.transform.position, target, 1 * Time.deltaTime);
Destroy (sphereInstance, 10);
}
}
}
Input.GetMouseButtonDown(0)is true, so your sphere will move exactly one time: during the first frame after a click. If that's not what you want, you may want to separate those functions. - rutter