Unity射线,鼠标点击

WALLdEMO:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;  
public class WALLdEMO : MonoBehaviour {

    // Use this for initialization
    public float sx;
    public float sy;
    public float ex;
    public float ey;
    public Transform BarrierParent;

    //预制体:预先制作好的游戏对象
    public GameObject Barrier1;
    void Start () {
        CreateBarrier();
    }
    
    // Update is called once per frame
    void Update () {
        
    }
    void CreateBarrier() {
        for (float i = sx; i <= ex; i += 1.55f) {
            for (float j = sy; j>= ey; j -= .6f)
            {
                GameObject barrier = GameObject.Instantiate(Barrier1);//克隆
                barrier.transform.position = new Vector3(i, j, BarrierParent.position.z);
                barrier.transform.parent = BarrierParent;
                //随机颜色,得到不同等级障碍物
                int index = Random.Range(0,Barrier.ColorArr.Length-1);
                barrier.GetComponent<Barrier>().OnChangeColor(index);
                barrier.GetComponent<Barrier>().HP = index + 1;
            }
        
        }
    }
}

WoodControl:

using UnityEngine;
using System.Collections;

public class WoodControl : MonoBehaviour {

    // Use this for initialization
    public Transform LP;
    public Transform RP;
    void Start () {
    
    }
    
    // Update is called once per frame
    //float nx=0;
    void Update () {
        float d = Input.GetAxis ("Horizontal");
        this.transform.Translate (d*12*Time.deltaTime,0,0);
        if (this.transform.position.x <= LP.position.x+1.5f)
            this.transform.position = new Vector3(LP.position.x+1.5f, this.transform.position.y, this.transform.position.z);
        if (this.transform.position.x >= RP.position.x-1.5f)
            this.transform.position = new Vector3(RP.position.x-1.5f, this.transform.position.y, this.transform.position.z);
    }

    
}





cube:

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

public class cube : MonoBehaviour {
    Rigidbody rg;
    bool isDead;
    // Use this for initialization
    void Start () {
        //记得加刚体
        rg = this.GetComponent<Rigidbody>();
        isDead = true;
        //给予一个初速度
        rg.velocity = Vector3.up * 3;

    }

    // Update is called once per frame
    void Update () {
        //
        //if (Input.GetMouseButtonDown(0))     
            if (isDead && Input.GetButtonDown("Jump")) 
             {
                //添加一个速度
                    rg.velocity = Vector3.up * 5;
            //添加一个力
            // rg.AddForce(Vector3.up * 300);
        }

    }
}
 

shoot:

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

public class shoot : MonoBehaviour {

    // Use this for initialization
    void Start () {
        
    }
    public GameObject bullet1;
     //public Transform bullet1;//????只是需要这个物体上的位置信息 ,而不是这个物体
    // Update is called once per frame
    void Update () {
        if (Input.GetMouseButtonDown(0))
        {
            //创建子弹
            CreateBullet();
        }
    }
    //刚体是组件 组件访问 GetCompon/ent
    void CreateBullet()
    {
        //创建一个指定类型的3D对象
        GameObject bullet = GameObject.CreatePrimitive(PrimitiveType.Cube);
        //初始化 子弹的位置
        bullet.transform.position = bullet1.transform.position;
        //改变大小
        bullet.transform.localScale = new Vector3(0.3f, 0.3f, 0.3f);
        //加上刚体的组件
        // bullet.AddComponent("Rigibody "); GameObject.AddComponent(string);已过时
        Rigidbody rg = bullet.AddComponent<Rigidbody>();
        //Transform  属性 forward返回该对象的正前方方向向量,Z正前方
        // rg.velocity = bullet1.forward * 10;  若定义的bullet1 定义的是Transform   
        rg.velocity = bullet1.transform.forward * 10;
    }
}

RayDemo:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RayDemo : MonoBehaviour
{
    GameObject currentClick;
    void Start()
    {
    }
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            //256:2的(层次)幂
            //
           int  LayerIndex = LayerMask.NameToLayer("star");
            if (Physics.Raycast(ray, out hit, int.MaxValue,/*256*/ LayerIndex)) 
            {
                currentClick = 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);
            //Ray r = new Ray(currentClick.transform.position + new Vector3(0, 0.5f, 0), Vector3.left);
            RaycastHit hit;
            
            if (Physics.Raycast(r, out hit, 0.5f, 256))
            {
                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)用来进行碰撞检测
 * 结构存在栈里面,值类型
 * 引用类型的对象存在堆
 * 
 * 案例讲:向上发射射线检测
 * 1.上下左右,只要检测到相同的颜色的格子就删除
 * 2.Layermask
 * 3.刚体
 */
/*
            * 射线检测主要是检测射线是否跟场景中碰撞体发生碰撞,相交
            进行射线检测,发生碰撞,就会碰撞信息存到hit里面;
            * 同时返回true,反之返回false,hit还是空的;
            * Raycast(Ray,out RaycastHit)
            * Raycast(Ray,out RaycastHit,float maxDistance,int layermask)
            */

test:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class test : MonoBehaviour
{

    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            //unity 如何将屏幕坐标转换为射线
            //将屏幕坐标转换为射线
            //当前鼠标位置的像素坐标:Input.mousePosition
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            //存储射线碰撞的信息(存储坐标 碰到的物体的信息)
            //面试
            RaycastHit hit;//值变量
            //只能和物体碰撞 在物理系统。若碰撞 返回true.发生碰撞,hit中会存入碰撞信息。
            //没有碰撞器,射线会穿过
            //射线检测:if (Physics.Raycast(ray,out hit))长度 2的层次方
            /*  Raycast(Ray,out RaycastHit)
             * Raycast(Ray,out RaycastHit,float maxDistance,int layermask)
                   */
            //Raycast 
            if (Physics.Raycast(ray, out hit, int.MaxValue, 256))
            {
                //print("发生碰撞,鼠标访问到对象");
                //获取对象
                // print:调试用
                //print("相交位置:" + hit.point);
                //print("碰撞的对象:" + hit.collider); 
                currentClick = hit.collider.gameObject;
                print("点击到一个对象");
                CastUp();
            }

        }

    }

     GameObject currentClick;
    void CastUp()
    {
        
        if (currentClick != null)
        {
            print("向上发射射线");
            //currentClick.transform.position:中心点
            //当前位置开始 发射一条向上的射线
            //new Vector3(0,0.5f,0)????
            Ray r = new Ray(currentClick.transform.position - new Vector3(0, 0.5f, 0), Vector3.down);
            RaycastHit hit;
            //Ray s = new Ray(currentClick.transform.position + new Vector3(0, 0.5f, 0), -Vector3.up);
            //RaycastHit hit1;
            if (Physics.Raycast(r, out hit, 0.5f, 256))
            {
                print("检测到一个对象");
                //判断颜色 返回物体组件
                //检测到的上面的对象                
                GameObject obj = hit.collider.gameObject;
                //GameObject obj1 = hit.collider.gameObject;
                //除了Transform 其他组件都可以使用这个泛型获得
                //获得组件网格渲染
                MeshRenderer mr = obj.GetComponent<MeshRenderer>();
                print("颜色:" + mr.material.color);
                //object :是所有的基类
                //获取该对象颜色
                Color a = mr.material.color;
                //获取该点击对象的颜色
                Color A = currentClick.GetComponent<MeshRenderer>().material.color;
                //判断颜色是否一样
                if (a.Equals(A))
                {
                    //删除
                    Destroy(obj);
                    Destroy(currentClick);
                    obj = null;
                    currentClick = null;
                }


            }
        }
    } 
              void check()
                {

                } 
}
/*结构存在栈里,值类型
 结构:所有数据类型 都是结构类型
 射线:起点 方向
  Ray:射线,起点和方向
 * 
 * 结构存在栈里面,值类型
 * 引用类型
TAG:是main camera,才是主摄像机
     */



_413:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class _413 : MonoBehaviour {
    //鼠标点击移动
    // Use this for initialization
    void Start () {
        MoveEndPos=this.transform.position;
    }
    //Vector3定义时,不需要赋初始值.Vector3:三维坐标
    Vector3 MoveEndPos;
    // Update is called once per frame
    void Update () {
        //左键摁下
        if(Input.GetMouseButtonDown(0))
        {
            //定义一射线
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            
            //计算射线的起点和终点。
            RaycastHit hit;
            if(Physics.Raycast(ray,out hit))
            {
                MoveEndPos = hit.point;
            }
        }
        this.transform.LookAt(MoveEndPos);//朝向问题
        this.transform.position = Vector3.MoveTowards(this.transform.position,  MoveEndPos, 0.05f);//第三个参数:移动速度,每一帧移动的距离
        
    }
}


createcube:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class createcube : MonoBehaviour {

    // Use this for initialization
    void Start () {

        //Invokes the method methodName in time seconds, then repeatedly every repeatRateseconds.在时间 秒 中调用方法方法名称,然后重复每个重复频率秒。

        //public void InvokeRepeating(string methodName, float time, float repeatRate);
        InvokeRepeating("create", 5f, Time.deltaTime * 40);
    }
     
    public  GameObject obj;
    // Update is called once per frame
    void Update () {
       // create();
    }
   // public GameObject cube;
    void create()
    {
        //if (Input.GetMouseButtonDown(0))
        //{
        //    float x = Random.Range(-5f, 5f);
        //    float z = Random.Range(-5f, 5f);
        //    //obj = GameObject.CreatePrimitive(PrimitiveType.Cube);
        //    obj = (GameObject)GameObject.Instantiate(obj);
        //    obj.transform.Translate(x, -1.3f, z);
        //    //若外边  private Transform obj1;
        //    // 可以 obj1.position = new Vector3(0, 0, 0);
        //}
        for (int count = 0; count < Random.Range(0, 2); count++)
        {
            //object
            Instantiate(obj, new Vector3(count, 1.3f, count), Quaternion.identity);
            //Quaternion.identity :The identity rotation(Read Only).标识旋转(只读)。
        }

    }
     
}



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

public class copy : 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;
            if (Physics.Raycast(ray,out hit))
            {
                print("触碰到物体");
                print("位置:" + hit.point);
            }
        }
       
        
    }
}


OnCollisionExit is called when this collider/rigidbody has stopped touching another rigidbody/collider.

当 collider/rigidbody停止触动另一个 rigidbody/collider时,OnCollisionExit被调用。

In contrast to OnTriggerExit, OnCollisionExit is passed the Collision class and not a Collider. The Collision class contains information about contact points, impact velocity etc. If you don't use collisionInfo in the function, leave out the collisionInfo parameter as this avoids unneccessary calculations. Note that collision events are only sent if one of the colliders also has a non-kinematic rigidbody attached.

相比OnTriggerExit,OnCollisionExit传递Collision类而不是Collider。Collision类包含接触点,碰撞速度等信息。在这个函数如果你不使用collisionInfo,删去collisionInfo参数以避免不必要的计算。注意,当其中至少一个碰撞盒附加非动力学刚体时碰撞事件才会发送。


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

public class cooperate : MonoBehaviour {

    // Use this for initialization
    void Start () {
        print(Time.deltaTime);
    }


    // Update is called once per frame
     public bool isRotate = false;
    void Update () {
        //Jump:空格
        if (Input.GetButtonDown("Jump"))
        {
            isRotate = !isRotate;
        }
        Rotate();
        RandomPosition();
    }
    void Rotate()
  {
        if (isRotate)
        {
            this.transform.Rotate(0, 1, 0);
        }
    }
    //if (Input.GetKeyDown(KeyCode.Space))
    //{
    //    jump();
    //}
    //else if (Input.GetMouseButtonDown(1)|| Input.GetMouseButtonDown(0)|| Input.GetMouseButtonDown(2))
    //{
    //    this.transform.position += new Vector3(0,0,0);
    //Random a = new Random();
    //}
    void RandomPosition()
    {
        //任意移动在平面上
        if (Input.GetButtonDown("Fire1"))
        {
            float x = Random.Range(-5f,5f);
            float z = Random.Range(-5f,5f);
            this.transform.position = new Vector3(x, 1.02f, z);

        }

        //else if (Input.GetKey(KeyCode.Space))
        //{
        //    jump();
        //}
        //KeyCode.Space:空格键
    }

    //Input




    void  jump()
    {
        //localScale:大小
        this.transform.position += new Vector3(0, 1, 0);
    }
    void CreateCube()
    {
        //PrimitiveType Cube;  
        //GameObject.CreatePrimitive();
    }


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

public class ActionOfMouse : MonoBehaviour {

    // Use this for initialization
    void Start () {
        //打印电脑帧数
        print(Time.deltaTime);
    }
    //Transform
    // Update is called once per frame
    void Update () {

        OnMouseEnter();
        print("鼠标在对象上"); 
         
    }
      void OnMouseUp()
    {
        this.transform.localScale -= new Vector3(1, 1, 1);
    }

    void OnMouseEnter()
    {
        this.transform.localScale = 2*new Vector3(1, 1, 1);
    }
}


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

public class ratation : MonoBehaviour {

    // Use this for initialization
    void Start () {
        
    }
    public Transform targetobject;
    public float speed = 1f;//旋转速度
    // Update is called once per frame
    void Update () {
        transform.RotateAround(targetobject.position, Vector3.up, speed);
    }
    
}


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

public class cooperate : MonoBehaviour {

    // Use this for initialization
    void Start () {
        print(Time.deltaTime);
    }


    // Update is called once per frame
     public bool isRotate = false;
    void Update () {
        //Jump:空格
        if (Input.GetButtonDown("Jump"))
        {
            isRotate = !isRotate;
        }
        Rotate();
        RandomPosition();
    }
    void Rotate()
  {
        if (isRotate)
        {
            this.transform.Rotate(0, 1, 0);
        }
    }
    //if (Input.GetKeyDown(KeyCode.Space))
    //{
    //    jump();
    //}
    //else if (Input.GetMouseButtonDown(1)|| Input.GetMouseButtonDown(0)|| Input.GetMouseButtonDown(2))
    //{
    //    this.transform.position += new Vector3(0,0,0);
    //Random a = new Random();
    //}
    void RandomPosition()
    {
        //任意移动在平面上
        if (Input.GetButtonDown("Fire1"))
        {
            float x = Random.Range(-5f,5f);
            float z = Random.Range(-5f,5f);
            this.transform.position = new Vector3(x, 1.02f, z);

        }

        //else if (Input.GetKey(KeyCode.Space))
        //{
        //    jump();
        //}
        //KeyCode.Space:空格键
    }

    //Input




    void  jump()
    {
        //localScale:大小
        this.transform.position += new Vector3(0, 1, 0);
    }
    void CreateCube()
    {
        //PrimitiveType Cube;  
        //GameObject.CreatePrimitive();
    }


}




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

public class ratation : MonoBehaviour {

    // Use this for initialization
    void Start () {
        
    }
    public Transform targetobject;
    public float speed = 1f;//旋转速度
    // Update is called once per frame
    void Update () {
        transform.RotateAround(targetobject.position, Vector3.up, speed);
    }
    
}




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

public class self : MonoBehaviour
{

    // Use this for initialization
    void Start()
    {

    }
    //自转
    //public Transform oneself;
    public float speed = 1f;
    // Update is called once per frame
    void Update()
    {
        //this.transform.Rotate(0,0.02f,0);
        //Vector3.up :0,1,0
        //Vector3.zero:0,0,0
        transform.Rotate(Vector3.up * speed, Space.World);
    }
}
原文地址:https://www.cnblogs.com/allyh/p/13069916.html