如何在鼠标光标处生成对象
How to spawn objects at mouse cursor
我希望能够实例化鼠标所在的对象。我试图这样做(下面的代码),但在我的尝试中,对象总是在屏幕中央生成。我该怎么做才能解决这个问题?
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];
}
}
}
}
我认为 Camera.ScreenToWorldPoint
return 是世界上的一个点,对应于您相机的 镜头 所在的位置。它不是 return 鼠标下几何体的世界坐标,我怀疑这就是您想要的。为此,您需要对场景进行光线投射并找到交点所在的位置。
如果您要进行 2D 项目,我建议您在鼠标位置进行光线投射并重新设置 Z 值:
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);
}
我希望能够实例化鼠标所在的对象。我试图这样做(下面的代码),但在我的尝试中,对象总是在屏幕中央生成。我该怎么做才能解决这个问题?
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];
}
}
}
}
我认为 Camera.ScreenToWorldPoint
return 是世界上的一个点,对应于您相机的 镜头 所在的位置。它不是 return 鼠标下几何体的世界坐标,我怀疑这就是您想要的。为此,您需要对场景进行光线投射并找到交点所在的位置。
如果您要进行 2D 项目,我建议您在鼠标位置进行光线投射并重新设置 Z 值:
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);
}