如何将Unity预制件移动到鼠标点击位置?

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

我该如何移动这个对象?
3个回答

1

目前看起来你正在移动附着在脚本上的GameObject,而不是你创建的GameObject。有两种方法可以实现这一点。

  1. 您可以将所有内容从 if(MouseButtonDown(0)) 语句移动到附加到立方体预制件的脚本中。但是,然后生成的每个预制件都会移动到相同的位置

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


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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接