Я работаю над платформерной игрой, я создал пользовательский интерфейс для здоровья и затем создал здоровье игрока. Но когда я создавал скрипт Sprike, он не работал. Как, когда я взаимодействую со спайком (с Box colider,является триггером) сбрасывает уровень.
Я также создал void Dead
, сбрасываю уровень, если curHealth <= 0
, но я не знаю, почему он перезапускает мой уровень, если у меня осталось 2 жизни (у игрока 3живет публично int maxHealth = 3;
)
Сценарий:
Сценарий Spikes:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spikes : MonoBehaviour
{
private Player player;
void Start(){
player = GameObject.FindGameObjectWithTag("Player").GetComponent<Player>();
}
void OnTriggerEnter2D(Collider2D col){
if(col.CompareTag("Player")) {
player.Damage(1);
}
}
}
Сценарий игрока:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Player : MonoBehaviour
{
public GameObject blood;
public float speed;
public float jumpForce;
private float moveInput;
private Rigidbody2D rb;
private bool isGrounded;
public Transform groundCheck;
public float checkRadius;
public LayerMask whatIsGround;
private int extraJumps;
public int extraJumpsValue;
private bool facingRight = true;
public int curHealth;
public int maxHealth = 3;
void Start(){
curHealth = maxHealth;
extraJumps = extraJumpsValue;
rb = GetComponent<Rigidbody2D>();
}
void FixedUpdate(){
isGrounded = Physics2D.OverlapCircle(groundCheck.position, checkRadius, whatIsGround);
moveInput = Input.GetAxis("Horizontal");
rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
if(facingRight == false && moveInput > 0){
Flip();
} else if(facingRight == true && moveInput < 0){
Flip();
}
}
void Update(){
if(isGrounded == true){
extraJumps = extraJumpsValue;
}
if(Input.GetKeyDown(KeyCode.UpArrow) && extraJumps > 0){
rb.velocity = Vector2.up * jumpForce;
extraJumps--;
} else if(Input.GetKeyDown(KeyCode.UpArrow) && extraJumps == 0 && isGrounded == true){
rb.velocity = Vector2.up * jumpForce;
}
if(curHealth > maxHealth){
curHealth = maxHealth;
}
if(curHealth <= 0){
Die ();
}
}
void Flip(){
facingRight = !facingRight;
Vector3 Scaler = transform.localScale;
Scaler.x *= -1;
transform.localScale = Scaler;
}
void Die(){
//Restart
Application.LoadLevel(Application.loadedLevel);
}
void OnCollisonEnter2D(Collision2D col){
if (col.gameObject.tag.Equals("Spikes")){
Instantiate ( blood, transform.position, Quaternion.identity);
gameObject.SetActive(false);
}
}
public void Damage(int dmg) {
curHealth -= dmg;
}
}