unity3D 从摄像机发射射线,检测画线

最近做项目的时候,有一个需要从摄像机发出一条射线,当射线检测到有碰撞物体的时候,点击鼠标左键开始画线。我是创立了一个平板drawing,当然Cube什么的也是可以的。
c#脚本代码,将这个脚本拖到摄像机里,然后拖拽材质到画线材质,拖拽碰撞体到脚本那里即可以。
代码脚本(附有注释):


using UnityEngine;
using System.Collections;

public class test : MonoBehaviour {

//-----------划线所能够用到材质  
 public Material lineMaterial  ;  
//  
  int maxPoints = 5000;  
  //全局变量的定义方法  
 public static float lineWidth = 4.0f;  
 int minPixelMove = 2;  // Must move at least this many pixels per sample for a new segment to be recorded  
 public Vector2[] linePoints;  
 private VectorLine  line ;  
 private int  lineIndex = 0;  
  private   Vector2   previousPosition;  
  private int  sqrMinPixelMove ;  
  private bool canDraw = false;  
//记录当下画板的位置,判断平板是否平移等  
  public Vector3 boardPosition;  
  public GameObject board;  
//记录当下画板的大小,判断画板是否缩放等     
 public Vector3 boardScale;   
//初始化平板的大小与位置  
void IntializeScaleAndPosition()  
{  
    boardPosition=Camera.mainCamera.WorldToScreenPoint(board.transform.position);  
    boardScale=board.transform.localScale;  
      
}  
// 初始化  
void Start () {  
    linePoints = new Vector2[maxPoints];  
    line = new VectorLine("DrawnLine", linePoints,lineMaterial, lineWidth, LineType.Continuous);  
    sqrMinPixelMove = minPixelMove * minPixelMove;  
    IntializeScaleAndPosition();  
}  
// Update is called once per frame  
void Update () {  
    Vector2 mousePos = Input.mousePosition;  
    //当画板移动时,将所有的点按照统一方向移动相同的距离
   //当前画板的位置  
   Vector3 currentBoardPositon=Camera.mainCamera.WorldToScreenPoint(board.transform.position);  
      
    //画板的移动距离  
    Vector3  moveDistance=currentBoardPositon-boardPosition;  
      
    if(moveDistance.x!=0||moveDistance.y!=0)  
    {  
        //将所有的画下的点都平移  
        for(int i=0;i sqrMinPixelMove && canDraw)  
        {  
            previousPosition = linePoints[++lineIndex] = mousePos;  
            line.minDrawIndex = lineIndex - 1;  
            line.maxDrawIndex = lineIndex;  
            if (lineIndex >= maxPoints - 1) canDraw = false;  
            Vector.DrawLine(line);  
        }                 
    }     
}  

你可能感兴趣的:(unity3D 从摄像机发射射线,检测画线)