MoveTowards()没有移动我实例化的GameObjects

时间:2017-03-08 01:08:31

标签: c# unity3d

当玩家点击时,我试图使用RayCast找到玩家正在看的点,然后实例化一个球体对象。然后我尝试使用MoveTowards()来尝试使球体朝着玩家正在看的点移动。出于某种原因,当我运行我的游戏时,点击生成球体,但它们根本不会从它们的起始位置移动。

这是我的代码:

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 个答案:

答案 0 :(得分:0)

使用if else语句调用单独的spheremove函数,因为这些函数仅在鼠标停止时触发。将目标传递给球体移动函数并实例化并将球体移动到那里。

答案 1 :(得分:0)

最好将单独的脚本附加到您的球体对象中以使用移动并将目标传递到其中。像这样的东西

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

}

在SphereBehaviour脚本中实例化时指定目标。

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