物理的衝突イベント


//出所はゴールドメタルの講座!
  • OnCollisionEnter(Collision col)
  • OnCollision(Collision col)
  • OnCollisionExit(Collision col)
  • 衝突時に色を変更するクラス

    MeshRenderer mesh;
        Material mat;
    
        // Start is called before the first frame update
        void Start()
        {
            mesh = GetComponent<MeshRenderer>();
            mat = mesh.material;
        }
        
        //CollisionEnter : 물리적 충돌이 시작할 때 호출되는 함수.
        void OnCollisionEnter(Collision collision)
        {
            if(collision.gameObject.name == "MyBall")
                mat.color = new Color(0, 0, 0);
        }
    
        private void OnCollisionExit(Collision collision)
        {
            if (collision.gameObject.name == "MyBall")
                mat.color = new Color(0, 1, 0);
        }

    Triggerを使用したキューブのアップロード


    //物理的な衝突ではないので、衝突情報はありません.
    //したがってパラメータはcolliderとして宣言されます.
    private void OnTriggerStay(Collider other)
    {
    if (other.gameObject.name == "Cube")
    rigid.AddForce(Vector3.up * 3, ForceMode.Impulse);
    }
  • Cubeを透明にすると、透明な空間に入ると昇ります.
    =>fpsゲームでは、特定の空間に入ると、ボールを飛ばす動作を実現できます.
  • この場合、alpha値を下げることで透明にすることができる.