My script puts an object at the position of the mouse, regardless of the position.
I’d like to limit where I can place the object to a small area around the player sprite.
Say if mouse X if greater than (X position + a little) of the players X than the object wont Instantiate. I’ve tried if statements along these lines but haven’t been able to get it to work.
Here is the placement script.
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);
}
}
}
GrKl
2
This should do the job. Limit if X and Z distances between player and mousePOS are smaller than 2.
I moved your input check to Update, so you don’t call “PlantInGround” at all if you did not click.
I also commented a line in your code that I don’t understand, where you “mousePOS .z += 12”. Why is this before the following line? Your setting mousePOS.z then change completely mousePOS on the next line…
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 ((Mathf.Abs(player.transform.position.x - mousePOS.x) < 2f) && (Mathf.Abs(player.transform.position.z - mousePOS.z) < 2f))
{
Instantiate(seedlings, mousePOS, Quaternion.identity);
}
Debug.Log(mousePOS);
}
Okay so for whatever reason GrKls code did not work for me. So I took it and changed the if statement and it worked exactly how I wanted it to. Thanks for the help man. Leaving this hear for others.
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);
}
}
}