1.1.0 Unity零基础入门2——Roll a Ball

1. 游戏界面

 

2.代码

 1 //FoodRotate - - 控制cube旋转
 2 
 3 using System.Collections;
 4 using System.Collections.Generic;
 5 using UnityEngine;
 6 
 7 public class FoodRotate : MonoBehaviour {
 8 
 9     // Use this for initialization
10     void Start () {
11         
12     }
13     
14     // Update is called once per frame
15     void Update () {
16         //控制cube旋转 - - Vector3(x,y,z)围绕某一轴旋转
17         //乘以Time.deltaTime * 60 每秒旋转60°
18         transform.Rotate(new Vector3(1, 1, 1)*Time.deltaTime*60);
19     }
20 }
FoodRotate - - 控制cube旋转
 1 //FollowCamera - - 使相机跟随小球
 2 
 3 using System.Collections;
 4 using System.Collections.Generic;
 5 using UnityEngine;
 6 
 7 public class FollowCamera : MonoBehaviour {
 8 
 9     public Transform boll;
10     private Vector3 offset;
11 
12     // Use this for initialization
13     void Start () {
14         
15         //把相机和小球的位置相减得到相对距离
16         offset = transform.position - boll.position;
17     }
18     
19     // Update is called once per frame
20     void Update () {
21 
22         //此时赋值后相机能保持相对地跟随小球
23         /* 如果不这么做当小球移动旋转时,相机自身也会旋转 */
24         transform.position = boll.position + offset;
25     }
26 }
FollowCamera - - 使相机跟随小球
//MoveSphere - - 控制小球移动

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI; //声明Text类时要用

public class MoveSphere : MonoBehaviour {

    private Rigidbody boll;         //小球
    private int score;              //分数
    public Text text;               //分数text
    public GameObject WinText;      //游戏胜利的text
       
    // Use this for initialization
    void Start () {

      boll = GetComponent<Rigidbody>();
    }
    
    // Update is called once per frame
    void Update () {
        float h = Input.GetAxis("Horizontal");
        float v = Input.GetAxis("Vertical");

        boll.AddForce(new Vector3(h, 0, v)*2);

    }

    //碰撞检测
    private void OnCollisionEnter(Collision collision)
    {
        //collision.collider 获取碰撞到的物体身上的collider组件
        //string name = collision.collider.name 获取碰撞到的物体的名字
        //print(name) 在控制台输出name
        if(collision.collider.tag=="Food")
        {
            
            Destroy(collision.collider.gameObject);
        }
    }

    //触发检测(勾选Box collider里的isTrigger)
    private void OnTriggerEnter(Collider collider)
    {
       if(collider.tag=="Food")
        {
            score++;
            text.text = "Score : " + score;
            Destroy(collider.gameObject);

            //当分数到达后显示胜利的text
            if(score==9)
            {
                WinText.SetActive(true);
            }
        }
    }
}
MoveSphere - - 控制小球移动

 

posted @ 2018-05-08 00:34  QQW的进化之旅  阅读(279)  评论(0编辑  收藏  举报