The question is answered, right answer was accepted
How do I Instantiate a prefab at the x axis position of where the UI button was clicked
So right now i have an invisible button in my 3d game scene that when clicked i need to find the right worldspace position to drop the newly instantiated coin. I am close BUT if i don't click in the center of the button and drop straight down then the prefabs drop in strange places along the x axis. I need to limit the "drop zone" of the instantiated prefab to the width of the button so they only fall onto the playable area of the scene.
//variables
public Button dropButton;
public GameObject coin;
Ray ray;
RaycastHit hit;
// Start is called before the first frame update
void Start()
{
Button button = dropButton.GetComponent<Button>();
button.onClick.AddListener(DropCoin);
}
// Update is called once per frame
void Update()
{
}
public void DropCoin()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
GameObject instantiatedCoin;
instantiatedCoin = Instantiate(coin, new Vector3(hit.point.x, 9.5f, 10.5f), Quaternion.identity) as GameObject;
}
}
}
Answer by Owen-Reynolds · Nov 07, 2020 at 05:22 AM
Is there a ground object behind the button which you expect the raycast to hit? I wonder if it's hitting something else on the way, like the button. That would mess up x if you have a perspective camera. Try printing hit.transform.name
to check.
A fix would be setting the raycast's latermask to only hit the ground.
No i want the ray to only hit the button, as the button acts as the x boundary to drop my coin. it works to a degree and "i think" i found the issue but still cant figure out how to solve it. The issue is my perspective camera has a x rotation of 45 to angle it down towards the play area. Due to this angle if i hit the bottom of the button the coin drops correct but as i hit higher and higher on the button the coins move further out along the x axis out of the playable area.
Position and angle of the camera shouldn't matter. A hit on your button at point p is a hit at p, no matter where the ray came from. Your button may not be correctly aligned with the "ground". $$anonymous$$aybe set the coins isKenimatic to freeze them, then look at exactly where they spawned.
So tested your theory and your correct that when the ray hits the floor below the game table thats when the coin drops wrong. Ill have to put a transparent object in the way to block the floor at height of game table behind that part of my button i guess?
Use a layermask. They tell the raycast to ignore certain objects. For only the button, I think it would be the "UI" layer. Or make a collider with layer "coinTarget" and use that.