首页 > 解决方案 > 玩家没有受到尖刺的伤害

问题描述

我正在开发一个平台游戏,我为 Health 创建了 UI,然后我创建了 Player health。但是当我创建 Sprike 脚本时,它没有工作。就像,当我与尖峰交互时(使用 Box colider,是触发器)它重置级别。

我还创建了一个void Dead,如果 ,则重置级别curHealth <= 0,但我不知道为什么如果我还剩 2 条生命它会重新启动我的 lvl(玩家有 3 条公共生命int maxHealth = 3;

脚本是:

尖峰脚本:

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;
    }
}

标签: c#unity3d

解决方案


好的在刚体上有一个名为碰撞检测的属性将其更改为离散的(如果它是连续的)并重试


推荐阅读