限制我可以在 mousedown 上实例化的位置?

Limit where I can Instantiate on mousedown?

我的脚本将一个对象放在鼠标的位置,而不考虑位置。

我想将对象的放置位置限制在玩家精灵周围的一小块区域。

假设如果鼠标 X 大于玩家 X 的(X 位置 + 一点),则对象不会实例化。我已经尝试过这些语句中的 if 语句,但无法使其正常工作。

这是放置脚本。

 public GameObject seedlings;
 public GameObject player;
 Vector3 mousePOS = Input.mousePosition;

 // Use this for initialization
 void Start(){}
 // Update is called once per frame
 void Update()
 {
     PlantInGround();
 }
 void PlantInGround()
 {
     Vector3 mousePOS = Input.mousePosition;

         if (Input.GetMouseButtonDown(0))
         {
             mousePOS.z = +12;
             mousePOS = Camera.main.ScreenToWorldPoint(mousePOS);
             Instantiate(seedlings, (mousePOS), Quaternion.identity);
             Debug.Log(mousePOS);
         }
 }

感谢任何帮助。

检查您的幼苗位置是否靠近玩家的位置:

float maxDist = 3F; //radius within the player that the seedling can be instantiated
if ( (mousePOS - player.transform.position).magnitude < maxDist )
{
  //Do Something
}

您可以比较距离的平方,因为 magnitude 涉及一个 Sqrt() 调用,这是昂贵的,但考虑到您只是在单击鼠标时执行此操作,所以这并不重要很多。

当然,您必须确保您的播放器距离相机的前视方向大约 12 个单位。假设您这样做:

mousePOS.z = +12;
mousePOS = Camera.main.ScreenToWorldPoint(mousePOS);

这就是最终的效果。留给别人。老实说,我不知道为什么坐标刚好对齐。感谢@Lincon 的帮助。

public class PlantItem:MonoBehaviour {

public GameObject seedlings;
public GameObject player;
Vector3 mousePOS = Input.mousePosition;

void Update()
{
    if (!Input.GetMouseButtonDown(0))
    {
        PlantInGround();
    }
}

void PlantInGround()
{
    Vector3 mousePOS = Input.mousePosition;

    mousePOS.z = +12;
    mousePOS = Camera.main.ScreenToWorldPoint(mousePOS);
    if (((player.transform.position.y < mousePOS.y + 0.5) && (player.transform.position.y > mousePOS.y - 1.5)) && ((player.transform.position.x < mousePOS.x + 1) && (player.transform.position.x > mousePOS.x - 1)))
    {
        Instantiate(seedlings, mousePOS, Quaternion.identity);

    }
}

}