Ive looked everywhere for a simple tutorial on ray casting but all I have found is the script reference page which dosent really help with what I need. But I don’t know anything about ray casting. Instead of having a bullet prefab coming out of my gun I have heard a ray cast would be better, can anyone help me with this?
This is the best raycasting post I’ve come across link text
Slow projectiles like rockets or cannon balls may be instantiated. For fast projectiles like bullets, it’s better to use a Raycast instead (in the First Person Tutorial, the rockets are instantiated, while the machine gun uses raycast). The script below shows how to use raycast to shoot: when the Shoot function is called, a Raycast is done in the weapon forward direction; if nothing hit, nothing happens; if it’s an enemy, you can instantiate blood at the hit point and send a message to make the enemy reduce its health; if another thing is hit, you can emit sparks at the hit point.
var shotSound: AudioClip; // drag a shot sound here, if any var bloodPrefab: GameObject; // drag the blood prefab here, if any var sparksPrefab: GameObject; // drag the sparks prefab here, if any function Shoot(){ if (shotSound) audio.PlayOneShot(shotSound); // play the shot sound var hit: RaycastHit; if (Physics.Raycast(transform.position, transform.forward, hit)){ // prepare rotation to instantiate blood or sparks var rot = Quaternion.FromToRotation(Vector3.up, hit.normal); if (hit.transform.tag == "Enemy"){ // if enemy hit... if (bloodPrefab) Instantiate(bloodPrefab, hit.point, rot); // make it bleed... hit.transform.SendMessage("ApplyDamage", 5, SendMessageOptions.DontRequireReceiver); // and consume its health } else { // otherwise emit sparks at the hit point if (sparksPrefab) Instantiate(sparksPrefab, hit.point, rot); } } }
This script shoots in the forward direction of the object to which it’s attached. If the weapon model has a different orientation, child to it an empty object and align it to the shooting direction, then attach the script to this object.
NOTE: You must add a ApplyDamage function to the enemy, like this:
var health = 100; function ApplyDamage(damage: int){ health -= damage; if (health <= 0){ // enemy dies } }