Cursos / Jogos Digitais / Desenvolvimento com Motores de Jogos I / Aula

arrow_back Aula 14 - Criação de Elementos em Tempo de Execução, Dano e Elementos Coletáveis

2. Adicionando dano ao Jogo

Por fim, precisamos de uma pequena alteração no método Break, uma vez que o chão dos buracos atua diretamente com esse método. Caso o personagem vá quebrar, a barra de vida deve ser completamente zerada, independentemente de seu valor anterior. Fazemos isso alterando o valor da propriedade Color do FillRect, componente do Slider que vimos em aulas anteriores. O código completo do novo PlayerController, incluindo as alterações no método Break, podem ser vistos na Listagem 5.

x
1
using System.Collections;
2
using System.Collections.Generic;
3
using UnityEngine;
4
using UnityEngine.UI;
5
6
public class PlayerController : MonoBehaviour {
7
8
    private bool jumping = false;
9
    private bool grounded = false;
10
    private bool doubleJump = false;
11
    private bool doubleJumping = false;
12
    private bool movingRight = true;
13
    private bool active = true;
14
15
    private Rigidbody2D rigidBody;
16
    private Animator ani;
17
    public Transform groundCheck;
18
    public LayerMask layerMask;
19
    
20
    public float acceleration = 100f;
21
    public float maxSpeed = 10f;
22
    public float jumpSpeed = 500f;
23
24
    private float startingHealth = 100f;
25
    private float currentHealth;
26
    private Slider healthBar;
27
28
    // Use this for initialization
29
    void Awake () {
30
        rigidBody = GetComponent<Rigidbody2D> ();
31
        ani = GetComponent<Animator>();
32
        healthBar = FindObjectOfType<Slider>();
33
        currentHealth = startingHealth;
34
        healthBar.value = currentHealth; 
35
36
    }
37
38
    // Update is called once per frame
39
    void Update() {
40
        if (active) {
41
            if (grounded) {
42
                doubleJump = true;
43
            }
44
45
            if (Input.GetButtonDown("Jump")) {
46
                if (grounded) {
47
                    jumping = true;
48
                    doubleJump = true;
49
                } else if (doubleJump) {
50
                    doubleJumping = true;
51
                    doubleJump = false;
52
                }
53
            }
54
        }
55
    }
56
57
    //Called in fixed time intervals, frame rate independent
58
    void FixedUpdate() {
59
        if (active) {
60
            float moveH = Input.GetAxis ("Horizontal");
61
62
            ani.SetFloat("speed"Mathf.Abs(moveH));
63
64
            grounded = Physics2D.OverlapBox (groundCheck.position, (new Vector2 (1.3f0.2f)), 0flayerMask);
65
66
            ani.SetBool("grounded"grounded);
67
            ani.SetFloat("vertSpeed"rigidBody.velocity.y);
68
69
            if (moveH < 0 && movingRight) {
70
                Flip();
71
            } else if (moveH > 0 && !movingRight) {
72
                Flip();
73
            }
74
75
            rigidBody.velocity = new Vector3 (maxSpeed * moveHrigidBody.velocity.y0);
76
77
            if (jumping) {
78
                rigidBody.AddForce(new Vector2(0fjumpSpeed));
79
                jumping = false;
80
            }
81
            if (doubleJumping) {
82
                rigidBody.velocity = new Vector2 (rigidBody.velocity.x0);
83
                rigidBody.AddForce(new Vector2(0fjumpSpeed));
84
                doubleJumping = false;
85
            }
86
        }
87
    }
88
89
    void Flip() {
90
        movingRight = !movingRight;
91
        transform.localScale = new Vector3((transform.localScale.x * -1), transform.localScale.ytransform.localScale.z);
92
    }
93
94
    public bool isGrounded () {
95
        return grounded;
96
    }
97
98
    public void Break () {
99
        active = false;
100
        //rigidBody.bodyType = RigidbodyType2D.Static;
101
        ani.SetBool("active"false);
102
        ani.Play("Break");
103
        FindObjectOfType<GameController>().Break();
104
        healthBar.fillRect.GetComponentInChildren<Image>().color = new Color(0,0,0,0);
105
    }
106
107
    public void LevelEnd () {
108
        active = false;
109
        rigidBody.bodyType = RigidbodyType2D.Static;
110
        ani.SetBool("active"false);
111
        ani.Play("CelebrationRoll");
112
        FindObjectOfType<GameController>().LevelEnd();
113
    }
114
115
    public float HealthChange (float value) {
116
        if (currentHealth + value < startingHealth) {
117
            currentHealth += value;
118
        } else {
119
            currentHealth = startingHealth;
120
        }
121
122
        healthBar.value = currentHealth;
123
124
        if (currentHealth <= 0) {
125
            Break();
126
        }
127
128
        return currentHealth;
129
    }
130
}
131
Listagem 5 - Código alterado do script PlayerController, com o novo método HealthChange, as novas variáveis e as alterações realizadas no método Break.
Fonte: Elaborada pelo autor

Versão 5.3 - Todos os Direitos reservados