public class cube : MonoBehaviour {
public Sphere sphere;
float des; //与主角之间的距离
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
des = Vector3.Distance(sphere.transform.position, this.gameObject.transform.position);
if(des < 3 && des > 2)
{ //看向主角并跟随;
this.gameObject.transform.LookAt(sphere.transform.position);
this.gameObject.transform.Translate(Vector3.forward * Time.deltaTime);
}
}
public class Sphere : MonoBehaviour { Ray ray; RaycastHit rh; float dis; //鼠标与球的距离 Vector3 tar; //目标点 private Vector3 lastPos; //上一次运动停止的位置 private float lastTime; //上一次运动停止的时间 // Use this for initialization void Start () { lastPos = transform.position; lastTime = 0; } // Update is called once per frame void Update () { if (Input.GetMouseButtonDown(0)) { //左键,获得鼠标射线 ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray, out rh)) { if (rh.collider.name == "Plane") //判碰撞物体是否是地面 { tar = rh.point; //Debug.Log(rh.point+"2"); } } } dis = Vector3.Distance(this.gameObject.transform.position, tar); if (dis > 0.5f) //鼠标点击与球的距离 { this.gameObject.transform.LookAt(tar); this.gameObject.transform.Translate(Vector3.forward * Time.deltaTime); } if (dis < 3) { if (lastPos != transform.position) //如果上次静止的位置和当前位置不相同,就更新上次静止的位置和时间 { lastTime = Time.time; lastPos = transform.position; } if (Time.time - lastTime > 2) //如果静止时间>2s { lastTime = Time.time; Destroy(this.gameObject); } } } }
作者:Czhenya
链接:https://czhenya.blog.csdn.net/article/details/77338141
来源:CSDN
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。