【发布时间】: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))
-
你可以更新你的第一段我无法理解它