0
votes

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);


    }

}



}
2
The code that spawns your sphere and the code that moves your sphere are both called only if 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
change if(Input.GetMouseButtonDown(0)) to if(Input.GetMouseButton(0)) - Cổ Chí Tâm
can you update your first paragraph i am unable to understand it - Muhammad Faizan Khan

2 Answers

0
votes

Use your if else statements to call a separate spheremove function since those only trigger when mouse is down. Pass the target to the sphere move function and instantiate and move the sphere there.

0
votes

it is better to attache a separate script into you sphere object to use move towards and pass the target into. Something like this

    Class SphereMover :MonoBehaviour
    {
        public GameObject target;
        void Update(){
               if(target !=null){
                   transform.position = Vector3.MoveTowards(transform.position, target, 1 * Time.deltaTime);
    }
    }

}

Assign target at the time of instantiaing in SphereBehaviour script.

    sphereInstance = Instantiate (spherePrefab, (player.TransformPoint (new Vector3 (1, -.5f, -2))), Quaternion.identity) as GameObject;
sphereInstance.GetComponent<SphereMover>().target = target;