【问题标题】:MoveTowards() not moving my instantiated GameObjectsMoveTowards() 不移动我实例化的游戏对象
【发布时间】:2017-03-08 01:08:31
【问题描述】:

当玩家点击时,我尝试使用 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);


    }

}



}

【问题讨论】:

  • 只有在Input.GetMouseButtonDown(0) 为真时才会调用生成球体的代码和移动球体的代码,因此球体将移动一次:在单击后的第一帧期间。如果这不是您想要的,您可能需要分离这些功能。
  • 将 if(Input.GetMouseButtonDown(0)) 更改为 if(Input.GetMouseButton(0))
  • 你可以更新你的第一段我无法理解它

标签: c# unity3d


【解决方案1】:

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

    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;

【讨论】:

    【解决方案2】:

    使用 if else 语句调用单独的 spheremove 函数,因为这些函数仅在鼠标按下时触发。将目标传递给球体移动函数并在此处实例化和移动球体。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多