Skip to content

Instantly share code, notes, and snippets.

@rockitude
Created June 10, 2014 21:40
Show Gist options
  • Save rockitude/fabe95016033bfd29f3e to your computer and use it in GitHub Desktop.
Save rockitude/fabe95016033bfd29f3e to your computer and use it in GitHub Desktop.
Dealing Ranged Damage with Raycasting in Unity 3D
var health = 100;
var health = 100;
#pragma strict
var fireballPrefab: GameObject;
var spawnLocation: Transform;
function Start () {
}
function Update () {
//create a Vector3 representing the forward direction
var forward: Vector3 = spawnLocation.TransformDirection(Vector3.forward) * 50;
//draw debug ray straight ahead
Debug.DrawRay(transform.position, forward, Color.green);
//shoot fireball
if(Input.GetButtonDown("Fire2")){
var spell = Instantiate(fireballPrefab, spawnLocation.position, spawnLocation.rotation);
//raycast - anything there?
var hit: RaycastHit; //create hit object to store raycast results
if(Physics.Raycast(spawnLocation.position, forward, hit)){ //if raycast hits something...
var enemy = hit.collider.gameObject; //get the GameObject that was hit
var eh = enemy.GetComponent(EnemyHealth); //get the EnemyHealth component from enemy
eh.health -= 10; //decrease health by 10
//change value on screen
var ehDisplay = GameObject.Find("Enemy_HealthDisplay");
var ehText = ehDisplay.GetComponent(GUIText);
ehText.text = "Enemy Health: " + eh.health;
}
}
}
#pragma strict
var waiting = false;
var waitUntil = 0;
function OnTriggerStay(){
var enemyHealth = GetComponent(EnemyHealth);
var ehDisplay = GameObject.Find("Enemy_HealthDisplay");
if(Input.GetButtonDown("Fire1")){
//decrease enemy health
enemyHealth.health -= 10;
print("Enemy took 10 damage.");
//change value on screen
var ehText = ehDisplay.GetComponent(GUIText);
ehText.text = "Enemy Health: " + enemyHealth.health;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment