C# 碰撞,射线,点击,周期函数等基本代码

using UnityEngine.SceneManagement;
 
SceneManager.LoadScene(0);
 
 
���� 
 Application.LoadLevel(Application.loadedLevelName);括号里面的参数是最后加载的场景名,也就是当前场景名
    
public class FirstDemo : MonoBehaviour {
    //重置时候,或者第一次被添加的时候执行的函数
    
    //void Reset() {//编辑状态下被调用的函数
    //    level = 1;
    //    Debug.Log("第一个执行的函数");
    //    print("我是reset");//通过集成而来的静态的方法;
    //}
   //每次对象激活就调用一次此函数,第二调用的函数
    void OnEnable() {
        print("我Cube是显示状态,激活状态");
    }
    //第一次调用该脚本:第一个被执行的函数是Awake
    void Awake() { 
        //唤醒:只执行一次,不可以被重复调用
        print("我CUbe是唤醒函数");
    }
    /*
     所有的对象都被唤醒之后,在执行update之前会先执行start,
     * 只执行一次;
     * Awake()本对象数据初始化
     * Start()访问组建,访问其他对象
     */
    void Start() {
        print("我是cube的start");
    }
    /*
     固定更新:每秒固定执行我们设置好的帧数
     */
    void FixedUpdate() { 
   /// 重复执行
    }
    
    // 跟电脑性能有关系,默认电脑大概50/s
    void Update () {
        //重复执行
    }
    //这一帧结束之前执行的函数
    void LateUpdate() { 
    
    }
    //处于未激活状态就调用此函数一次
    void OnDisable() {
        print("我处于未激活状态,隐藏");
    }
    
}  
 
 脚本默认继承Monobehaviour
 Monobehaviour:Behaviour:Component;
 大多数的脚本作为组件的方式添加游戏对象身上,不是一个组件不可以添加;
 Monobehaviour:Behaviour:Component:提供很属性让我们直接访问对象的相关组件,获取信息;
 * 提供方法访问改变游戏对象;
 Monobehaviour生命周期:一帧所有执行函数
 * 编辑状态:
 * Reset:脚本第一次被添加,或者按reset按钮就会调用一次该函数
 * 运行期间:
 * Awake()唤醒,只执行一次,第一个执行函数
 * OnEnable()激活时被调用,第一次运行对象被激活就调用一次,下次再激活再调用
 * 当所有对象的唤醒和OnEnable都执行完后,相当场景中游戏对象都创建完毕
 * Start()所有对象的唤醒和onenable都执行完后,才会执行start();
 * update()执行之前就会先到用Start();
 * Update()更新函数根据电脑性能来执行,大概50/s,不断重复执行;
 * FixedUpdate()固定更新,自定义帧频;
 * LateUpdate():所有物理函数,输入函数,以上函数都执行完毕后就调用执行函数,每帧都会调用
   OnDisable()未激活时就调用此函数,重复调用  
 * 通过键盘控制对象左右旋转,前后移动
 */
 
 
/*
 Input:访问输入设备:键盘,鼠标,摇杆,触屏,手机重力感应
 * GetKeyDown(KeyCode code)检测是否按下某个键,只检测一次
 * 按下那一瞬间返回true
 * GetKeyUp(KeyCode code)检测是否松开键盘的某一个键
 * 松开那一刻返回true
 * GetKey(KeyCode)
 * 只要一直按着一个键,就一直返回true,除非松开
GetMouseButtonDown()
 * GetMouseButtonUp()
 * GetMouseButton()
 */
 */
    

void OnMouseDown() {
        print("我按下鼠标");
    }
    void OnMouseUp() {
        print("我松开鼠标");
    }
    void OnMouseOver() {
        print("我在对象上");
    }
    void OnMouseEnter() {
        print("我进入对象");
    }
    void OnMouseExit() {
        print("我离开对象");
    }
 





 //Horizontal水平虚拟轴,控制左右移动或者左右旋转
        float angleSpd=Input.GetAxis("Horizontal");//AD左键右键
        this.transform.Rotate(0,angleSpd*20*Time.deltaTime, 0);
        float speed = Input.GetAxis("Vertical");
        this.transform.Translate(0, 0, speed * 20 * Time.deltaTime);




using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RayDemo : MonoBehaviour {

    // Use this for initialization
    void Start () { 
        
    }
    
    // Update is called once per frame
    void Update () {
        if (Input.GetMouseButtonDown(0))
        {
            //把屏幕坐标转换为射线
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            //存储射线碰撞的信息
            RaycastHit hit;
            /*
             * 射线检测主要是检测射线是否跟场景中碰撞体发生碰撞,相交
             进行射线检测,发生碰撞,就会碰撞信息存到hit里面;
             * 同时返回true,反之返回false,hit还是空的;
             * Raycast(Ray,out RaycastHit)
             * Raycast(Ray,out RaycastHit,float maxDistance,int layermask)
             */
            if (Physics.Raycast(ray, out hit,100,512)) {
                print("发生碰撞,鼠标访问到一个对象");
                print("相交位置:"+hit.point);
                print("碰撞的对象:" + hit.collider.gameObject);
            }
        }
    }
} 



void CastUp() {
        if (currentClick != null) {
            print("向上发射摄像");
            //发射一条向上的射线
            Ray r = new Ray(currentClick.transform.position+new Vector3(0,0.5f,0), Vector3.up);
            RaycastHit hit;
            if (Physics.Raycast(r,out hit,0.5f,256)) {
               // print("点击到一个对象");
                print("检测到一个对象");
                GameObject obj = hit.collider.gameObject;
                MeshRenderer mr=obj.GetComponent<MeshRenderer>();
                print("颜色:" + mr.material.color);
            }

        }
    }
 





using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RayDemo : MonoBehaviour {

    // Use this for initialization
    GameObject currentClick;
    void Start () { 
        
    }
    
    // Update is called once per frame
    void Update () {
        if (Input.GetMouseButtonDown(0))
        {
            //把屏幕坐标转换为射线
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            //存储射线碰撞的信息
            RaycastHit hit;
            /*
             * 射线检测主要是检测射线是否跟场景中碰撞体发生碰撞,相交
             进行射线检测,发生碰撞,就会碰撞信息存到hit里面;
             * 同时返回true,反之返回false,hit还是空的;
             * Raycast(Ray,out RaycastHit)
             * Raycast(Ray,out RaycastHit,float maxDistance,int layermask)
             */
            if (Physics.Raycast(ray, out hit,int.MaxValue,256)) {
                currentClick = hit.collider.gameObject;
                //print("发生碰撞,鼠标访问到一个对象");
                //print("相交位置:"+hit.point);
                //print("碰撞的对象:" + hit.collider.gameObject);
                print("点击到一个对象");
                CastUp();
            }
        }
    }
    void CastUp() {
        if (currentClick != null) {
            print("向上发射射线");
            //发射一条向上的射线
            Ray r = new Ray(currentClick.transform.position+new Vector3(0,0.5f,0), Vector3.up);
            RaycastHit hit;
            if (Physics.Raycast(r,out hit,0.5f,256)) {
               // print("点击到一个对象");
                print("检测到一个对象");
                //检测到的上面对象
                GameObject obj = hit.collider.gameObject;
                //获取组件网格渲染
                MeshRenderer mr=obj.GetComponent<MeshRenderer>();
                //获取该对象颜色
                Color c = mr.material.color;
                //获取点击对象的颜色
                Color currentC = currentClick.GetComponent<MeshRenderer>().material.color;
               //判断颜色是否一样
                if (c.Equals(currentC)) {
                    //删除
                    Destroy(obj);
                    Destroy(currentClick);
                    obj = null;
                    currentClick = null;
                }
            }

        }
    }
}
/*
 Ray:射线,起点和方向
 * RaycastHit:存储射线碰撞碰撞的信息;
 * Phyics.Raycast(Ray,out RaycastHit)用来进行碰撞检测
 * Phyics.Raycast(Ray,out RaycastHit,float maxDistance,int layermask)用来进行碰撞检测 

public class RayLayerDemo : MonoBehaviour {

    // Use this for initialization
    void Start () {
        
    }
    
    // Update is called once per frame
    void Update () {
        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            int layerIndex=LayerMask.NameToLayer("wall");
            print(1 << layerIndex);//位移运算
            if (Physics.Raycast(ray, out hit, int.MaxValue, 1<<layerIndex))//(int)Mathf.Pow(2,layerIndex)))
            {
                print("点击到一个对象");   
            }
        }
    }
}
 

public class GunFire : MonoBehaviour {

    // Use this for initialization
    public Transform BulletP;
    void Start () {
        
    }
    
    // Update is called once per frame
    void Update () {
        if (Input.GetMouseButtonDown(0)) {
            CreateBullet();
        }
    }
    void CreateBullet() {
        //创建一个指定类型的3D对象
        GameObject bullet = GameObject.CreatePrimitive(PrimitiveType.Sphere);
        //初始化子弹的位置
        bullet.transform.position = BulletP.position;
        bullet.transform.localScale = new Vector3(.3f, .3f, .3f);
        //加上刚体组件
        Rigidbody rg=bullet.AddComponent<Rigidbody>();
        //Transform 属性 forward返回该对象的正前方方向向量,Z正前方
        rg.velocity = BulletP.forward * 10;
    }
}

  

public class BallMove : MonoBehaviour {

    // Use this for initialization
    Rigidbody rg;
    bool isDead;
    void Start () {
        rg = this.GetComponent<Rigidbody>();
        isDead = true;
        rg.velocity = Vector3.up * 3;
    }
    
    // Update is called once per frame
    void Update () {
        if (isDead&&Input.GetButtonDown("Jump")) {
            //添加一个速度
            rg.velocity = Vector3.up * 5;
            //添加一个力
           // rg.AddForce(Vector3.up * 300);
        }
    }
    /*
     两个物体可以发生碰撞的条件:
     * 双方必须都有碰撞器
     * 一方必须要有刚体
     * 碰撞器有三个回调函数:
     * OnCollisionEnter(Collision obj)刚好接触,刚好发生碰撞那一刻调用函数,只调用一次
     * OnCollisionStay(Collision obj)碰撞中,逗留,只要两个物体没有分离,每帧都回响应该函数
     * OnCollisionExit(Collision obj)碰撞结束,退出碰撞,只执行一次
     * Collision返回当前发生碰撞的碰撞信息
     */
    void OnCollisionEnter(Collision obj) {
        isDead = false;
        print("跟我发生碰撞的对象:"+obj.gameObject);
        if (obj.gameObject.name == "Plane") rg.isKinematic = true;
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ControlB : MonoBehaviour {

    // Use this for initialization
    float speed;
    void Start () {
        speed = 0;
    }
    
    // Update is called once per frame
    void Update () {
       // float sx = Input.GetAxis("Horizontal");
        Move();
       
    }
    void Move() {
        if (Input.GetKey(KeyCode.A))speed = -.1f;
        else if (Input.GetKey(KeyCode.D))speed = .1f;
        else speed = 0;
        
        this.transform.Translate(speed, 0, 0);
    }
} 
 
public class RoleMove : MonoBehaviour {

    // Use this for initializatio
    CharacterController role;
    void Start () {
        role = this.GetComponent<CharacterController>();
       // role.Move(transform.forward * 2);
    }
    
    // Update is called once per frame
    void Update () {
        float speed = Input.GetAxis("Vertical");
        role.Move(transform.forward * speed*Time.deltaTime);
    }
}
  
    // Update is called once per frame
    void Update () {
        float speed = Input.GetAxis("Vertical");
        //动力学,只产生位移,不受重力影响
       // role.Move(transform.forward * speed*Time.deltaTime);
        role.SimpleMove(speed*transform.forward);//模拟重力
    }
    /*
     角色控制器的碰撞响应函数,只要发生碰撞就一直响应
     * 碰撞响应函数是在移动过程中发生碰撞才 响应
     */
    void OnControllerColliderHit(ControllerColliderHit obj) {
        if (obj.gameObject.tag.Equals("barrier"))
        {游戏对象
//
            Destroy(obj.gameObject);
        }
    
    }
}
 

 
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SnakeControl : MonoBehaviour {
    //蛇,父对象,保存子对象
    public Transform Snake;
    public GameObject Food;
    public GameObject Body;
    float currentTime = 0;
    float singleTime = 0.4f;
    GameObject firstBody;
    GameObject lastBody;
    void Start () {
      //  print(transform.forward);
        RandomFood();
    }
    void RandomFood() {
        int sx = Random.Range(-25, 25);
        int sz = Random.Range(-50, 50);
        GameObject food = GameObject.Instantiate(Food);
        food.transform.position = new Vector3(sx, 0.5f, sz); ;
    }
    // Update is called once per frame
    void Update () {
        if (currentTime >= singleTime) 
        {
            print("移动一次");
            currentTime = 0;
            Vector3 old = transform.position;
           // transform.Translate(transform.forward);
            //改变位置,产生位移的方法
            transform.position += transform.forward;
            if (firstBody != null) {
                firstBody.GetComponent<SnakeBody>().Move(old);
            }
        }
        if (Input.GetKeyDown(KeyCode.A))
        {
            transform.Rotate(0,-90,0);
            print("a"+transform.forward);
        }
        else if (Input.GetKeyDown(KeyCode.D))
        {
            transform.Rotate(0, 90, 0);
            print("D" + transform.forward);
        }
        currentTime += Time.deltaTime;
    }
    //LinkedList链表:数据结构,设计模式
    //碰撞到食物,食物需要消失,蛇身体增加一个
    void OnTriggerEnter(Collider obj) {
        //销毁食物
        Destroy(obj.gameObject);
        //重新随机食物
        RandomFood();
        //加一个身体
        AddBody();
    }
    void AddBody() {
        GameObject body = GameObject.Instantiate(Body);
        if(firstBody==null)firstBody = body;
        else if (lastBody == null)
        {
            lastBody = body;
            firstBody.GetComponent<SnakeBody>().Next = body;
        }
        else {
            lastBody.GetComponent<SnakeBody>().Next = body;
            lastBody = body;
        }
        
    
    }
} 
 
原文地址:https://www.cnblogs.com/allyh/p/13725810.html