-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProjectile.cs
58 lines (46 loc) · 1.43 KB
/
Projectile.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Projectile : MonoBehaviour {
public LayerMask collisionMask;
float speed = 10;
float damage = 1;
float lifetime = 3;
float skinWidth = .1f;
void Start() {
Destroy (gameObject, lifetime);
Collider[] initialCollisions = Physics.OverlapSphere (transform.position, .1f, collisionMask);
if (initialCollisions.Length > 0) {
OnHitObject(initialCollisions[0]);
}
}
public void SetSpeed(float newSpeed) {
speed = newSpeed;
}
void Update () {
float moveDistance = speed * Time.deltaTime;
CheckCollisions (moveDistance);
transform.Translate (Vector3.forward * moveDistance);
}
void CheckCollisions(float moveDistance) {
Ray ray = new Ray (transform.position, transform.forward);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, moveDistance + skinWidth, collisionMask, QueryTriggerInteraction.Collide)) {
OnHitObject(hit);
}
}
void OnHitObject(RaycastHit hit) {
IDamageable damageableObject = hit.collider.GetComponent<IDamageable> ();
if (damageableObject != null) {
damageableObject.TakeHit(damage, hit);
}
GameObject.Destroy (gameObject);
}
void OnHitObject(Collider c) {
IDamageable damageableObject = c.GetComponent<IDamageable> ();
if (damageableObject != null) {
damageableObject.TakeDamage(damage);
}
GameObject.Destroy (gameObject);
}
}