-
Notifications
You must be signed in to change notification settings - Fork 0
/
Projectile.cs
53 lines (43 loc) · 1.29 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
using UnityEngine;
using System.Collections;
public class Projectile : MonoBehaviour
{
public LayerMask collisionMask;
public Color trailColor;
float speed = 10;
float damage = 1;
float lifetime = 3;
float skinWidth = 0.1f;
void Start()
{
Destroy(gameObject, lifetime);
var initialCollisions = Physics.OverlapSphere(transform.position, 0.1f, collisionMask);
if (initialCollisions.Length > 0) OnHitObject(initialCollisions[0], transform.position);
GetComponent<TrailRenderer>().material.SetColor("_TintColor", trailColor);
}
public void SetSpeed(float newSpeed)
{
speed = newSpeed;
}
void Update ()
{
float moveDistance = speed * Time.deltaTime;
CheckCollisions(moveDistance);
transform.Translate(Vector3.forward * Time.deltaTime * speed);
}
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.collider, hit.point);
}
}
void OnHitObject(Collider c, Vector3 hitPoint)
{
var damageableObject = c.GetComponent<IDamageable>();
if (damageableObject != null) damageableObject.TakeHit(damage, hitPoint, transform.forward);
GameObject.Destroy(gameObject);
}
}