小球撞擊磚塊,小球和磚塊都必須有碰撞體,當小球撞擊到磚塊之后,小球消失,在小球原本位置再生成一個小球,點擊鼠標繼續撞擊,小球撞擊磚塊是被檢測者,在小球類中聲明委托和事件
Bug :當鼠標點擊的位置沒有磚塊時,沒有碰撞事件發生,小球不會消失,也不會重新生成小球。
小球腳本
usingUnityEngine;
usingSystem.Collections;
publicclassSphereScript:MonoBehaviour{
public delegate void DeadDelegate();
public event DeadDelegate deadEvent;
public bool flag;
voidOnCollisionEnter(Collision other){
if(!flag){
if(other.gameObject.name.Contains("Cube")){
flag=true;
Invoke("Dead",1);//隔幾秒調用方法
}
}
}
voidDead(){
deadEvent();
Destroy(gameObject);
}
}
游戲控制腳本GameController
usingUnityEngine;
usingSystem.Collections;
publicclassGameController:MonoBehaviour{
public GameObject ballPrefabs;
private GameObject ball;
voidStart(){
CreatBall();//游戲開始默認創建
}
voidUpdate(){
RaycastHit hit;
if(Input.GetMouseButtonDown(0)){
if(Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition),out hit)){
//給球添加一個指向當前鼠標點擊的點方向的力
Vector3 forceDir=(hit.point-ball.transform.position).normalized;
ball.GetComponent<Rigidbody>( ).AddForce(forceDir*20,ForceMode.Impulse);//瞬時力
}
}
}
voidCreatBall( ){
ball=Instantiate(ballPrefabs,newVector3(0,0.4f,-6.58f),Quaternion.identity)asGameObject;
ball.GetComponent<SphereScript>( ).deadEvent+=BallDead;//注冊事件
}
voidBallDead( ){
CreatBall( );
}
}