- Home /
How to Instantiate objects on Ray.Hit
Hey, I am working on a raycast system and whenever the particle instantiates, it seems to instantiate on the player. Anyone know why this is?
function RayShoot ()
{
//Tells us if a the Ray has hit something
var Hit : RaycastHit;
//Direction of the Ray that the player has sent out
var DirectionRay = transform.TransformDirection (Vector3.forward);
//Make sure the player cannot shoot while reloading
//Note: This only matters for ReloadTrigger as when
//AutoReloading, "BulletsLeft" already is equal to 0
if (IsReloading == false)
{
//Makes the Ray visible in Game inspector (for debugging perpouses)
Debug.DrawRay(transform.position , DirectionRay * Range , Color.red);
//If the Ray is sent out...
if(Physics.Raycast(transform.position , DirectionRay , Hit, Range))
{
//...and we have hit a "RigidBody" Physics Object
if(Hit.rigidbody)
{
//Make the object fly away by adding force to it
Hit.rigidbody.AddForceAtPosition(DirectionRay * Force , Hit.point);
//This finds the "ApplyDamage" function and does damage to the player/AI...Don't ask me
//How this works :P
Hit.collider.SendMessageUpwards("ApplyDamage", Damage, SendMessageOptions.DontRequireReceiver);
//Tell the console we have hit and applied force to the object
Debug.Log("Rigid Body has been Hit")
}
//If a RigidBody is not hit but an object with the Tag mudFloor...
else if(Hit.transform.tag == "mudFloor")
{
//...create the Particle effect
Instantiate(Particle1, transform.position, transform.rotation);
//Tell the console that the particle is instantiated
Debug.Log("Mud Particle Instantiated")
}
}
//Take away from our BulletsLeft for eveytime we have fired
BulletsLeft --;
if(BulletsLeft < 0){
//Make sure BulletsLeft cant go bellow "0"
BulletsLeft = 0;
}
if(BulletsLeft == 0){
//Automatic Reload if the Player is out of Ammo
Reload();
}
}
}
Posting the whole function might not have been necessary, but I thought it would help to prevent confusion ^^ Thank you in advance!
Answer by robertbu · Jun 01, 2013 at 05:31 PM
You are using transform.position when you instantiate which is the position you are raycasting from. Use Hit.point.
Instantiate(Particle1, Hit.point, transform.rotation);
You may or may not want transform.rotation for the rotation. Often the normal of the hit is used as part of this rotation to get the object to be aligned with the surface.
Ah thanks, I thought this was the problem, but I didn't know how to change it. Transform.rotation does seem to do the job just perfectly in this case...