- Home /
instantiate object and align with object surface
Hello,
I have a game with a level map and a script that generates objects randomly in a circle above it. Is there a way I could have the object actually use the surface objects y coordinate rather than floating down on to it from above? The surface object is not a flat surface you see.
I am guessing that I need to find the mesh vertices from the object I am wanting to stick my new object to, but am unsure how to go about it.
Any help greatly appreciated.
mmuller
Answer by Jesse Anders · Dec 22, 2010 at 05:49 PM
If the surface has a collider associated with it, you could perform a vertical raycast to find the y coordinate that you're looking for.
The map does indeed have a mesh collider associated to it, I will have a read up on raycasts - never had a cause to use them... until now it seems :)
Answer by mmuller · Dec 22, 2010 at 10:46 PM
For anyone that wants it or might find it useful this is the script that I attached to the prefab as it is instantiated, which then aligns it to the level map:
var hit : RaycastHit;
var down = Vector3(0,-1, 0);
if (Physics.Raycast (transform.position, down, hit)) {
var distanceToGround = hit.distance;
var currentPos = transform.position;
var newY = currentPos.y-distanceToGround;
transform.position = Vector3(currentPos.x, newY, currentPos.z);
}
This basically grabs the objects initial starting position (out of sight in my case at +1000 y and then instantly alters it to the underlying objects height by subtracting this distance from its initial position.
Thanks to Jesse for the pointer in using Raycasting to find the Vector3 of the object to stick to.
Hey so I have read your question about instantiating objects but I am having trouble with my script still. I am trying to make an RTS style game and i can't get the instantiated objects to the mouse location or to stick to a sphere. ($$anonymous$$y world is a sphere and the player walks around it.) What I intent is the player clicks a UI button, then drags it to a location and when the player releases the mouse they will place the object at the location where they released the mouse button. Here is my code so far which doesn't work:
using System.Collections;
using UnityEngine;
public class BuildingPlacement : $$anonymous$$onoBehaviour {
private Transform currentBuilding;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (currentBuilding != null) {
Vector3 m = Input.mousePosition;
m = new Vector3(m.x,m.y, transform.position.y);
Vector3 p = Camera.main.ScreenToWorldPoint(m);
currentBuilding.position = new Vector3 (p.x, 0, p.z);
}
}
public void SetItem(GameObject b) {
currentBuilding = ((GameObject)Instantiate(b)).transform;
}
}