- Home /
Raycast damage script
I am doing an IPhone shooter however i don't want to have a shoot button is there any way or thechnique (script) you know to shoot a raycast continuously out of the players gun so that when the ray makes contact with a box around the enemy it starts shooting and the bullets in the magazine go down?
Answer by aldonaletto · Jul 02, 2012 at 11:31 PM
Doing this in Update may cause excessive impact in the performance, but maybe a more spaced raycasting could solve the problem - something like this (weapon script):
var bullets: int = 100; // ammo count var shotSound: AudioClip; // drag the shot sound here var shotInterval: float = 0.25; // interval between shots var shotRange: float = 100; // range of the shot var shootEnabled: boolean = true; // allows disabling the shots
function Start(){ var trf = transform; // a little optimization while (true){ // loop forever if (shootEnabled && bullets > 0){ // if there are bullets and shooting enabled... var hit: RaycastHit; // do a raycast if (Physics.Raycast(trf.position, trf.forward, hit, shotRange)){ // if the enemy trigger childed to the enemy is hit... if (hit.transform.gameObject.CompareTag("EnemyTrigger")){ audio.PlayOneShot(shotSound); // play the shot sound... hit.transform.SendMessageUpwards("ApplyDamage", 5); // apply damage... bullets--; // and count the shot } } } yield WaitForSeconds(shotInterval); // always wait shotInterval } } You must have a function ApplyDamage(damage: float) in the enemy script, and the "box" you've mentioned must be a trigger volume childed to the enemy.
Answer by diddykonga · Jul 02, 2012 at 11:28 PM
using UnityEngine;
using System.Collections;
public class AutoShoot : MonoBehaviour
{
public float fireRate; // How quick to shoot
public float damage; // Damage to be applied
public float shootDistance; // How far to check for a hit
private bool canShoot;
void FixedUpdate ()
{
RaycastHit info;
if(Physics.Raycast(new Ray(transform.position, transform.forward), out info, shootDistance))
{
if(canShoot)
{
// Do damage stuff here
if(fireRate > 0)
{
canShoot = false;
Invoke("ShootDelay", fireRate); // Delay shooting
}
}
}
}
private void ShootDelay()
{
canShoot = true;
}
}
Here you go, i think this should work, i havent tested it though :)
Your answer
Follow this Question
Related Questions
Shooting automativly without using GetButton? 1 Answer
If statement calls itself randomly? 1 Answer
Raycast shoot not working properly 0 Answers
How to access component that the raycast hit 1 Answer
shooting multiple enemies using raycast 2 Answers