top of page

RayCastの当たった相手のHPを減らす

1.RayScript

  

 void Ray(){


        // outパラメータ用に、Rayのヒット情報を取得するための変数を用意
        RaycastHit hit;

        var isHit = Physics.Raycast (transform.position, transform.forward, out hit, 100);

        if (isHit) {


            Debug.DrawRay (transform.position, transform.forward * hit.distance);

            // Rayがhitしたオブジェクトのオブジェクト名を取得
            string hitName = hit.collider.gameObject.name;

            //ヒットしたオブジェクトの名前がTESTなら
            if (hitName.Equals("TEST")) 
            {
                //10ダメージを与える
                hit.collider.GetComponent<HP>().TakeDamage(10);

            }


            //TEST以外の名前なら
            else 
            {

            }

        }
        else

        {
            Debug.DrawRay (transform.position, transform.forward * 100);
        }
            
    }        

 

2.HPScript

    public const int maxHealth = 100;
   public int health = maxHealth;

    public void TakeDamage(int amount)
    {
        health -= amount;
        if (health <= 0)
        {
            health = 0;
            Debug.Log("Dead!");
        }
    }

bottom of page