- Home /
Raycast + Instantiate
Hello there,
This script is called "Raymouse" and it's inside the main camera:
public var turretModel: GameObject;
function Update () {
var ray: Ray = camera.ScreenPointToRay (Input.mousePosition);
//Debug.DrawRay (ray.origin, ray.direction * 10, Color.yellow);
var raycastHit: RaycastHit;
if(Physics.Raycast(transform.position, ray.direction, raycastHit)){
//print("RaycastHit " + raycastHit.collider.gameObject.name);
if(raycastHit.collider.gameObject.name=="base"){
if(Input.GetKeyDown("mouse 0")){
var newTurret: GameObject;
newTurret = Instantiate(turretModel, raycastHit.collider.gameObject.transform.position, raycastHit.collider.gameObject.transform.rotation);
Destroy(raycastHit.collider.gameObject);
}
}
}
}
It instantiates an object when the user clicks a certain game object. But, depending on the order in which the objects are instantiated, it blocks when you try to instantiate something behind. I have attached a picture which shows what I just meant:
For it to work, I have to instantiate the ones in the back first. But it would be good if it worked in any order.
One thing I forgot to add... These cylinders have a huge sphere collider around them, that may be stopping the ray from getting to the cubes that need to colide with the ray.
What would be a good solution...? I'd greatly appreciate help...
i'll add this as a comment since you answered this yourself. your ray casting is hitting the giant sphere colliders. why do they need to be giant? if they absolutely need to be, i believe there's another raycast function that will return an array of everything the ray hits and you can iterate that and ignore the sphere colliders and only process the hits that make sense for instantiating new objects.
here's the return all hits function: http://unity3d.com/support/documentation/ScriptReference/Physics.RaycastAll.html
Jester, thank you very much for the help. I will look into it.
I tried to follow spinaljack's advice and give you the up vote, but I cuoldn't find that function. I hope my gratitude will suffice.
Answer by spinaljack · May 01, 2010 at 09:24 AM
You should give jester the up vote as he pretty much answered your question. Also, if you don't need to click on the blocks again after setting them you can change them to the ignore rays layer
Answer by VegaVG · Nov 07, 2012 at 11:16 PM
Another solution might be using capsule colliders instead of sphere colliders, if you are using cylinders