- Home /
Raycast and Instantiate
I have a problem with my bullet script. The problem is when i shoot something, the object was exploded first even the instantiated projectile didn't touches the object. here's my script. ammoCount is int projectile is rigidbody force is float damage is float shoot is audioclip
function Fire(){
var direction = transform.TransformDirection(Vector3.forward);
var hit : RaycastHit;
if (Physics.Raycast (transform.position, direction,hit,range)){
if(hit.rigidbody) hit.rigidbody.AddForceAtPosition (force * direction, hit.point);
var instantiatedProjectile : Rigidbody = Instantiate(projectile, transform.position, transform.rotation);
InstantiatedProjectile.velocity = transform.TransformDirection(Vector3(0,0,speed));
Physics.IgnoreCollision(instantiatedProjectile.collider,transform.root.collider);
audio.PlayOneShot (shoot);
ammoCount --;
//instantiatedProjectile.collider.SendMessageUpwards("ApplyDamage", damage, SendMessageOptions.DontRequireReceiver);
hit.collider.BroadcastMessage("ApplyDamage",damage, SendMessageOptions.DontRequireReceiver);
}
}
Answer by aldonaletto · Dec 24, 2011 at 10:53 AM
You're messing two different things: when shooting with Raycast, no projectile is instantiated - it's the best method to shoot fast projectiles like gun bullets, for instance (you can't see a gun bullet, only its effects); when instantiating a projectile (recommended method for slow projectiles like rockets), you must place the hit code (damage, impact force, explosion etc.) in the projectile's script OnCollisionEnter function - thus only when (and if) the projectile hits something you will see its effects.
The Raycast only version could be like this:
function Fire(){ audio.PlayOneShot (shoot); ammoCount --; var direction = transform.TransformDirection(Vector3.forward); var hit : RaycastHit; if (Physics.Raycast (transform.position, direction, hit, range)){ if(hit.rigidbody) hit.rigidbody.AddForceAtPosition (force * direction, hit.point); // apply the damage: hit.collider.SendMessageUpwards("ApplyDamage", damage, SendMessageOptions.DontRequireReceiver); } }while the projectile only version could be something like this:
function Fire(){ audio.PlayOneShot (shoot); ammoCount --; var direction = transform.TransformDirection(Vector3.forward); var instantiatedProjectile : Rigidbody = Instantiate(projectile, transform.position, transform.rotation); InstantiatedProjectile.velocity = direction * speed; Physics.IgnoreCollision(instantiatedProjectile.collider,transform.root.collider); }This must be in the projectile script:
function OnCollisionEnter(coll: Collision){ // send message to the object hit, not to the bullet: coll.collider.SendMessageUpwards("ApplyDamage", damage, SendMessageOptions.DontRequireReceiver); Destroy(gameObject); // destroy the bullet }