2017-04-18 56 views
0

我想能够实例化鼠标所在的对象。我试图做到这一点(下面的代码),但在我的尝试中,对象总是在屏幕中心产生。我能做些什么来解决这个问题?如何在鼠标光标处产生对象

using System.Collections; 
using System.Collections.Generic; 
using UnityEngine; 

public class CraftingControl : MonoBehaviour 
{ 

    public GameObject[] selectedObjectArray = new GameObject[3]; 
    public GameObject selectedObject; 
    // Use this for initialization 


    void Update() 
    { 
     if (selectedObject == null) 
     { 
      return; 
     } 
     if (Input.GetMouseButtonDown(0))//Here im getting postion and spawning objects 
     { 
      Vector3 tempMousePost = Input.mousePosition; 
      Vector3 mousePost = Camera.main.ScreenToWorldPoint(tempMousePost); 
      mousePost.y = 0; 
      Instantiate(selectedObject, mousePost, transform.rotation); 

     } 

    } 
    void OnGUI() 
    { 

     if (Input.GetKey(KeyCode.C)) 
     { 
      GUI.Box(new Rect(100, 100, 300, 300), "Crafting"); 
      if (GUI.Button(new Rect(125, 125, 100, 50), "Campfire")) 
      { 
       selectedObject = selectedObjectArray[0]; 
      } 

      if (GUI.Button(new Rect(125, 200, 100, 50), "Tent")) 
      { 
       selectedObject = selectedObjectArray[1]; 
      } 
      if (GUI.Button(new Rect(125, 275, 100, 50), "Fence")) 
      { 
       selectedObject = selectedObjectArray[2]; 
      } 
     } 
    } 
} 
+0

你构建一个2D或3D游戏? – pasotee

+0

@pasotee将一个2D物体放入一个3d世界将会很有趣,特别是如果我们不知道它应该如何放置的话。 –

+2

您不应该在游戏开发中使用'OnGUI'(又名“立即模式GUI”)。它仅用于创建编辑器控件您需要使用新的[UI系统](https://docs.unity3d.com/Manual/UISystem.html)。 –

回答

4

我认为相应于相机的镜头回报Camera.ScreenToWorldPoint点在世界上。它不会返回鼠标下的几何体的世界坐标,我怀疑是你想要的。为此,您需要在场景中进行光线投射并找到交点所在的位置。

0

我建议你在鼠标位置光线投射,并设置Z值回来,如果你要一个2D项目:

Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); 
RayCastHit rayHit; 
     if (Physics.Raycast(ray, out rayHit)) 
     { 
      Vector3 position = rayHit.point; 
      position.z = 0f; 
      Instantiate(yourGameObject, position, Quaternion.Identity); 
     }