射線拓展

小球撞擊磚塊,小球和磚塊都必須有碰撞體,當小球撞擊到磚塊之后,小球消失,在小球原本位置再生成一個小球,點擊鼠標繼續撞擊,小球撞擊磚塊是被檢測者,在小球類中聲明委托和事件

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( );

}

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容