I'm working on a 3D game in Unity and I'm having a problem trying to spawn an object exactly in front of a wall in my game, like hanging a picture on it. I don't want the object to look like it's too far from the wall or overlapping the wall.
public void SpawnPrefab(Transform prefab)
{
compSize = prefab.gameObject.GetComponent<Collider>().bounds.size.z;
Vector3 mousePosition, targetPosition;
InputManager inputManager;
inputManager = prefab.gameObject.GetComponent<InputManager>();
mousePosition = Input.mousePosition;
targetPosition = Camera.main.ScreenToWorldPoint(new Vector3(mousePosition.x,mousePosition.y,mousePosition.z + compSize/2 + wallSize/2));
prefab.localPosition = targetPosition;
if(isAlreadyClicked == false)
{
GameObject comp = (GameObject) Instantiate(prefab.gameObject, new Vector3(prefab.transform.position.x, prefab.transform.position.y, prefab.transform.position.z + compSize/2 + wallSize /2), prefab.transform.rotation);
isAlreadyClicked = true;
}
}
I tried adding float value on the mouseposition.z
like mouseposition.z + <somefloatvalue>
but it doesn't seem working like how I wanted because I have different object with different sizes, where some objects spawn at the back of the wall, while some will spawn too far at the front from the wall.
Update: I managed to get the accurate z position for the spawning process, but there's something wrong with its x and y position, it's not spawning based on the mouseclick position.
public void SpawnPrefab(Transform prefab)
{
clicked = false;
compSize = prefab.gameObject.GetComponent<Collider>().bounds.size.z;
Vector3 mousePosition, targetPosition;
InputManager inputManager;
inputManager = prefab.gameObject.GetComponent<InputManager>();
mousePosition = Input.mousePosition;
targetPosition = Camera.main.ScreenToWorldPoint(new Vector3(mousePosition.x,mousePosition.y,mousePosition.z));
ray = Camera.main.ScreenPointToRay(targetPosition);
float rayDistance;
if(plane.Raycast(ray, out rayDistance))
{
prefab.localPosition = ray.GetPoint(rayDistance);
Debug.Log("clicked");
if(isAlreadyClicked == false)
{
OnClickedButton();
GameObject comp = (GameObject) Instantiate(prefab.gameObject, new Vector3(targetPosition.x, targetPosition.y, frontWall.gameObject.transform.position.z + compSize - wallSize), prefab.transform.rotation);
isAlreadyClicked = true;
Debug.Log(clicked);
}
}
}
I don't know what is happening...