3

我创建了一个加载预制件并移动它的 unity3d 应用程序。我可以使用世界坐标加载立方体预制件。我想将此对象移动到鼠标单击位置。为了完成这项工作,我使用下面的代码。我的对象不会移动到任何地方。

public GameObject[] model_prefabs;

void Start () {
    //for (int i = 0; i < 1; i++) {
    int i = 0;
        Instantiate (Resources.Load ("Cube"), new Vector3 (i * 1.8F - 8.2f, 0, 0), Quaternion.identity);
    //}
}

void Update() {

    if (Input.GetKey("escape"))
        Application.Quit();

    if (Input.GetMouseButtonDown (0)) {

        Debug.Log ("mouseDown = " + Input.mousePosition.x + " " + Input.mousePosition.y + " " + Input.mousePosition.z);
        Plane p = new Plane (Camera.main.transform.forward , transform.position);
        Ray r = Camera.main.ScreenPointToRay (Input.mousePosition);
        float d;
        if (p.Raycast (r, out d)) {
            Vector3 v = r.GetPoint (d);
            //return v;
            Debug.Log ("V = " + v.x + " " + v.y + " " + v.z);
            transform.position = v;
        }
        else {
            Debug.Log ("Raycast returns false");
        }
    }
}

我从鼠标点击位置转换为世界坐标。他们看起来很合适。

mouseDown = 169 408 0
V = -5.966913 3.117915 0

mouseDown = 470 281 0
V = -0.1450625 0.6615199 0

mouseDown = 282 85 0
V = -3.781301 -3.129452 0

我怎样才能移动这个对象?

4

3 回答 3

1

现在看起来您正在移动脚本附加到的游戏对象,而不是您创建的游戏对象。有两种方法可以做到这一点。

  1. 您可以将 if(MouseButtonDown(0)) 语句中的所有内容移动到附加到 Cube 预制件的脚本中。但是你生成的每一个预制件都会移动到同一个地方。

  2. 你可以添加一个变量 GameObject currentObject; 然后在你的 Start() 函数中说 currentObject = Instantiate (Resources.Load ("Cube"), new Vector3 (i * 1.8F - 8.2f, 0, 0), Quaternion.identity); 并在您的更新函数中写入 currentObject.transform.position = v;

于 2015-06-02T15:12:56.427 回答
0

我使用下面的代码。这个对我有用。

void Start () {
    for (int i = 0; i < 3; i++) {
        gO[i] = Instantiate (Resources.Load ("Cube"), new Vector3 (i * 1.8F - 8.2f, 0, 0), Quaternion.identity) as GameObject;
    }
}

void Update() {

    if (Input.GetKey("escape"))
        Application.Quit();
#if UNITY_EDITOR
    if (Input.GetMouseButtonDown (0)) {
        Debug.Log ("mouseDown = " + Input.mousePosition.x + " " + Input.mousePosition.y + " " + Input.mousePosition.z);
        Plane p = new Plane (Camera.main.transform.forward , transform.position);
        Ray r = Camera.main.ScreenPointToRay (Input.mousePosition);
        float d;
        if (p.Raycast (r, out d)) {
            Vector3 v = r.GetPoint (d);

            for (int i = 0; i < 3; i++) {
                gO[i].transform.position = v;
                v.y = v.y - 2f;
            }
        }
    }
#endif
于 2015-06-03T06:23:09.093 回答
0

你可以使用这个。只需检查哪个预制件处于活动状态。

public GameObject activePrefab;
Vector3 targetPosition;

void Start () {

    targetPosition = transform.position;
}
void Update(){

    if (Input.GetMouseButtonDown(0)){
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;

        if (Physics.Raycast(ray, out hit)){
            targetPosition = hit.point;
            activePrefab.transform.position = targetPosition;
        }
    }
}
于 2015-10-31T07:33:32.810 回答