- Home /
Spawning above the terrain
For my multiplayer game, I want random spawning. This is what I'm using:
Network.Instantiate (Player, Vector3 (Random.Range (5, 95), transform.position.y+4, Random.Range (5, 95)), transform.rotation);
It doesn't work, but it isn't what I want anyway. How could I make it so that it always spawns a bit above the ground (on the y axis)?
Answer by Nicolaj Schweitz · Nov 28, 2013 at 09:52 PM
Hey! I have a script like this, however not taking the object's pivot into account as Ashkan_gc
Instantiate a prefab with the following script as a component.
Put the ground in a layer called ground.
Set the mask on the script to the ground layer.
using UnityEngine; using System.Collections; public class PutObjectOnGround : MonoBehaviour { public LayerMask mask = -1; float radius; void Start () { // set the vertical offset to the object's collider bounds' extends if (GetComponent<Collider>() != null) { radius = GetComponent<Collider> ().bounds.extents.y; } else { radius = 1f; } // raycast to find the y-position of the masked collider at the transforms x/z RaycastHit hit; // note that the ray starts at 100 units Ray ray = new Ray (transform.position + Vector3.up * 100, Vector3.down); if (Physics.Raycast(ray, out hit, Mathf.Infinity, mask)) { if (hit.collider != null) { // this is where the gameobject is actually put on the ground transform.position = new Vector3 (transform.position.x, hit.point.y + radius, transform.position.z); } } } }
Answer by Ashkan_gc · Jun 11, 2011 at 05:01 AM
first do a raycast toward ground and find it's position and then spawn a litle bit above it. it depends on the pivot of your object too. you should calculate the distance between pivote and bottom of your object and then position it based on that. procedural object placement is a really fun topic.
Hmm, the object isn't in any particular place. The spawner is just an empty GameObject.
Your answer
Follow this Question
Related Questions
Procedural Terrain? 3 Answers
Need help with randomizing starting location of terrains 0 Answers
Random Terrain in 2d Game? 0 Answers
Random Terrain Generation 2 Answers
How to access property of a prefab before Instantiating. 1 Answer