- Home /
Instantiate objects level with surface
Currently I'm working on adding a building functionality to a game and have run into something that I can't quite figure out how to do. Currently the build script makes a ray to the mouse position and has a semi-transparent preview of the model follow it. Upon clicking, a non-transparent version of the model is instantiated at that location. While this works fine, the problem is that we want the user to be able to place objects on walls and ceilings.
Currently this is the result of placing a few traffic cones:
The desired effect would be:
Any ideas on how to go about this? I've been racking my brain for awhile now and cant seem to think of any solution.
Current code: (added some comments)
var s : Transform; var b : GameObject; var buildtimer = 2; var nextbuild = 0;
function Update () { //Make ray to mouse position var ray = Camera.main.ScreenPointToRay(Input.mousePosition); var hit : RaycastHit;
/* If ray hits a surface within a 10 radius of player,
show the transparent build preview by enabling
it's renderer, disable renderer if it's over 10 */
if(Physics.Raycast(ray, hit, 10)){
if (hit.collider.tag != "BuildObject"){ //Make sure ray isn't hitting preview
var a = hit.point;
for (var child : Transform in s) {
if(child.renderer)
child.renderer.enabled = true;
}
s.position = a;
}
}else{
for (var child : Transform in s) {
if(child.renderer)
child.renderer.enabled = false;
}
}
}
function Fire () { //Fire function is called seperately by the build tool var ray = Camera.main.ScreenPointToRay(Input.mousePosition); var hit : RaycastHit;
if (Time.time < nextbuild)
return;
if(Physics.Raycast(ray, hit, 10)){
Instantiate(b, hit.point, Quaternion.identity);
nextbuild = Time.time + buildtimer;
}
}
Answer by hijinxbassist · Jun 18, 2012 at 05:16 AM
Look into the surfaces Normal. This will give you the correct face alignment. RaycastHit will contain the contacts normal and use the normal to re align your object correctly.
var rot = Quaternion.FromToRotation(Vector3.up, hit.normal);
Instantiate(cone,hit.point,rot);
Yes! Thank you so much for that, forgot about surface normals
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Place the object inside the surface when it jerks out of the surface 0 Answers
How to diappear a line renderer from start and end position of line 1 Answer
I want to add stripes at varying lengths on my object. How do I do that? 2 Answers
Animating an object so it doesn't bounce to the initial location the animation was recorded 1 Answer