Well, I am now moving on to weapon raycasting. I Have modeled a weapon, and it’s animaton. So now i was wondering as to how i would go about, to make the weapon raycast in a certain direction, and maybe have a sprite or a particle where it hits.
// we need a RaycastHit variable to be able to store hit information:
var hit : RaycastHit;
//Than we need to create the direction of the raycast (it could be just Vector3.forward or something)
var fwd = GameObject.FindWithTag("MainCamera").transform.TransformDirection (0, 0, 1);
//Now we raycast the ray and check if we hit something (check the Physics.Raycast in the reference)
if (Physics.Raycast(GameObject.FindWithTag("MainCamera").transform.position, fwd, hit, 1000)) {
//Did we hit a rigidbody? if so, than apply force to it
if(hit.rigidbody)
{
hit.rigidbody.AddForceAtPosition (-hit.normal * 900, hit.point);
//I use this to add an impact sound
Instantiate(impactMetal, hit.point, transform.rotation);
}
//no matter what we hit, we instantiate an explosion (which is a GameObject), that gets
// the normal of the surface we have hit and rotates itself so it aligns well
explosionRotation = Quaternion.FromToRotation(Vector3.up, hit.normal);
Instantiate(explosion, hit.point, explosionRotation);
}
Note that explosion is a variable - var explosion : GameObject
in the “fwd” variable, just put some direction, I’m using this to achieve nice accuracy.