射线拓展

2017-04-18  本文已影响9人  胤醚貔貅

小球撞击砖块,小球和砖块都必须有碰撞体,当小球撞击到砖块之后,小球消失,在小球原本位置再生成一个小球,点击鼠标继续撞击,小球撞击砖块是被检测者,在小球类中声明委托和事件

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

}

}

上一篇 下一篇

猜你喜欢

热点阅读