1. 程式人生 > 實用技巧 >Ruby's Adventure 07 採集生命道具 回血

Ruby's Adventure 07 採集生命道具 回血

向地圖中新增元件CollectibleHealth

新增Box Collider 2d新增碰撞資訊,並選擇is Trigger.

我們希望為生命道具新增動畫,選中CollectibleHealth,在Animation中create,和之前建立人物動畫類似的操作。然後Add property,選擇transform中的Scale

我們點選面板上的這個圖案,期望追蹤每一幀中Scale的變化。

然後回到動畫幀,將自動增加的一幀刪除,(在inspector面板)調整第一幀的X、Z軸數值稍稍增大,這樣使得物體變得更扁(或者你希望此刻物品形狀拉長的化就增大Y的數值),在第二幀將物品拉長(增大Y的數值)。並複製第一幀放到最後,執行發現我們就做出了物品運動的動畫。

回血功能

新建指令碼ItemHealth,進入指令碼,因為這個指令碼是對碰撞檢測進行一個設定所以可以刪除Strat 和 Update方法。

新增OnTriggerEnter2D

然後我們連結人物的指令碼Playercontal(你自己設定的指令碼名),如下

private void OnTriggerEnter2D(Collider2D collision)
{
    PlayerContal contal = collision.GetComponent<PlayerContal>();
}

然後我們需要進行一下判斷,如果人物碰到回血道具,則生命加1,並且摧毀物體:

if
(contal) { //每次接觸血量增加1 contal.ChangedHealth(1); //在人物觸碰到物品後對物品進行銷燬 Destroy(gameObject); }

ChangedHealth是我們在Playercontal腳本里面進行的設定。

更改後的程式碼如下:

 1 using System.Collections;
 2 using System.Collections.Generic;
 3 using UnityEngine;
 4 
 5 public class PlayerContal : MonoBehaviour
 6 {
 7
public float speed = 5f; 8 //定義血量 9 public int maxHealth = 5;    //定義人物最大血量 10 public int _currentHealth;   //人物當前血量 11 12 Rigidbody2D rbody; 13 private Animator _animator; 14 15 private float _x; 16 private float _y; 17 18 private Vector2 lookDir = Vector2.down;//向量向下 19 private Vector2 currentInput; 20 21 public int Health => _currentHealth; 22 //返回當前血量 23 24 private void Start() 25 { 26 rbody = GetComponent<Rigidbody2D>(); 27 _animator = GetComponent<Animator>(); 28 //初始化 29 _currentHealth = 1; //測試 30 } 31 32 private void Update() 33 { 34 _x = Input.GetAxis("Horizontal"); 35 _y = Input.GetAxis("Vertical"); 36 37 Vector2 movement = new Vector2(_x, _y); 38 39 //動畫部分,移動發生時,對朝向進行賦值 40 if(!Mathf.Approximately(movement.x, 0.0f) || !Mathf.Approximately(movement.y, 0.0f)) 41 { 42 lookDir.Set(movement.x, movement.y); 43 //對朝向進行歸一化,更好的控制人物 44 lookDir.Normalize(); 45 } 46 //選擇SetFloat和之間設定的浮點型進行對應 47 //lookx looky 就是之前設定的blend tree中的名稱 48 _animator.SetFloat("lookx",lookDir.x); 49 _animator.SetFloat("looky",lookDir.y); 50 _animator.SetFloat("speed", movement.magnitude); 51 //magnitude(求模)是將數值變換限制在我們規定的範圍內 52 53 currentInput = movement; 54 } 55 56 private void FixedUpdate() 57 { 58 Vector2 position = rbody.position; 59 position += currentInput * speed * Time.deltaTime; 60 rbody.MovePosition(position); 61 } 62 63 public void ChangedHealth(int amount) 64 { 65 _currentHealth = Mathf.Clamp(_currentHealth + amount, 0, maxHealth); 66 //現有血量,最小值,最大值 67 //對血量範圍做出限制 68 print("Health" + _currentHealth); 69 } 70 }

如插入程式碼所示。(๑ᵔ⌔ᵔ๑)