- Home /
Question by
oinkoinkflapflap · Mar 02, 2013 at 12:49 PM ·
instantiateraycasttagmouse position
mouse position on tag
how do i make the following javascript only instantiate when a certain tag is selected?
var bullet : Transform;
function Update () {
if(Input.GetMouseButtonDown(0)){
var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
var hit : RaycastHit;
if(Physics.Raycast(ray,hit,200)){
Instantiate(bullet, hit.point, Quaternion.identity);
}
}
}
thanks in advance!
Comment
Best Answer
Answer by AlucardJay · Mar 02, 2013 at 01:03 PM
Ok so you're almost there right. Look at where this would fit in. You cast a ray, but then you want to check out what it hit before doing anything else. So you hit a collider, it belongs to a gameObject, you want that tag :
if(Physics.Raycast(ray,hit,200)){
// What did i hit ?
Debug.Log( " I hit tag : " + hit.collider.gameObject.tag );
then to check a condition of something , use if
if ( hit.collider.gameObject.tag == "TagImLookingFor" )
{
// now I hit the tagged object fore sure !
}
put it all together
var bullet : Transform;
function Update () {
if(Input.GetMouseButtonDown(0)){
var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
var hit : RaycastHit;
if(Physics.Raycast(ray,hit,200)){
// What did i hit ?
Debug.Log( " I hit tag : " + hit.collider.gameObject.tag );
if ( hit.collider.gameObject.tag == "TagImLookingFor" ){
// now I hit the tagged object fore sure !
Instantiate(bullet, hit.point, Quaternion.identity);
}
}
}
}
ah that's what i missed, i put if(hit == gameObject.tag == "area"){ i needed collider rather than ==, thanks allot alucardi! appreciated!