aboutsummaryrefslogtreecommitdiff
path: root/Assets/Scripts/Bullet.cs
blob: 5e8b1fc2a67bcdae4fbf35a21d37cdf950343669 (plain) (blame)
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Bullet : MonoBehaviour {
  public string colour = "yellow";
  public float damage = 1f;

  public AudioClip bounceNoise;
  public float bounceNoiseVolume = 1.0f;
  public AudioClip hitWallNoise;
  public float hitWallNoiseVolume = 1.0f;
  public AudioClip hitEnemyNoise;
  public float hitEnemyNoiseVolume = 1.0f;
  public AudioClip genericHitNoise;
  public float genericHitNoiseVolume = 1.0f;

  public bool bounceOnWrongDoors = true;

  private bool leftPlayer = false;

  private Rigidbody2D body;
  private AudioSource audio;

  void Start() {
    body = GetComponent<Rigidbody2D>();
    audio = GetComponent<AudioSource>();
  }

  void Update() {
    if (body.velocity.x < 0) {
      transform.localScale = new Vector2(-1, 1);
    } else if (body.velocity.x > 0) {
      transform.localScale = new Vector2(1, 1);
    } else {
      transform.rotation = Quaternion.Euler(new Vector3(0, 0, 90));
    }
  }

  void OnTriggerEnter2D(Collider2D collider) {
    if (!leftPlayer) {
      leftPlayer = true;
      return;
    }

    if (genericHitNoise) audio.PlayOneShot(genericHitNoise, genericHitNoiseVolume);

    GameObject other = collider.gameObject;

    switch (other.tag) {
      case "Door":
        DoorLogic dl = other.GetComponent<DoorLogic>();
        if (dl.colour == this.colour) {
          dl.Open();
          Die();
        } else {
          if (bounceOnWrongDoors) { this.Bounce(); } else { Die(); }
        }
        break;

      case "Player":
        CharacterControl cc = other.GetComponent<CharacterControl>();
        cc.Damaged();
        Die();
        break;

      case "Enemy":
        if (hitEnemyNoise) audio.PlayOneShot(hitEnemyNoise, hitEnemyNoiseVolume);
        ICanDie icd = other.GetComponent<ICanDie>();
        if (icd) icd.Hit(damage);
        Die();
        break;

      case "Projectile":
        // do nothing
        break;

      default:
        if (hitWallNoise) audio.PlayOneShot(hitWallNoise, hitWallNoiseVolume);
        Die();
        break;
    }
  }

  void Die() {
    GetComponent<SpriteRenderer>().enabled = false;
    GetComponent<BoxCollider2D>().enabled = false;

    Invoke("ReallyDie", 3f);
  }

  void ReallyDie() {
    Destroy(this.gameObject);
  }

  void Bounce() {
    if (bounceNoise) audio.PlayOneShot(bounceNoise, bounceNoiseVolume);
    body.velocity = new Vector2(body.velocity.x * -1, body.velocity.y);
  }
}