在unity中,用鼠标画出图案并设置碰撞和重量,蛮牛上看到的代码如下:
/// <summary>
/// 画线,脚本随便挂载,要求Camera的Projection设置为Orthographic
/// </summary>
public class DrawLine : MonoBehaviour
{
/// <summary>
/// 划线的宽度
/// </summary>
public float width = 0.1f;
/// <summary>
/// 划线的颜色
/// </summary>
public Color color = Color.grey;
/// <summary>
/// 画出来的图案
/// </summary>
private LineRenderer currentLR;
/// <summary>
/// 上一个位置点
/// </summary>
private Vector2 previousPoint;
/// <summary>
/// 当前位置点
/// </summary>
private Vector2 latestPoint;
private void Update()
{
if(Input.GetMouseButtonDown(0))
{
//线条渲染
currentLR = new GameObject("LineRenderer").AddComponent<LineRenderer>();
currentLR.material = new Material(Shader.Find("Sprites/Default")) { color = color };
currentLR.widthMultiplier = width;
//不使用世界坐标
currentLR.useWorldSpace = false;
//设置初始位置个数为1
currentLR.positionCount = 1;
//设置第一个线段位置信息
currentLR.SetPosition(0, (Vector2)Camera.main.ScreenToWorldPoint(Input.mousePosition));
//更新数据
previousPoint = (Vector2)Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
else if(Input.GetMouseButton(0))
{
//如果当前位置不等于上一个位置,也就是按下鼠标后移动了,才会画线,但是要求Camera的Projection设置为Orthographic
if(previousPoint != (Vector2)Camera.main.ScreenToWorldPoint(Input.mousePosition))
{
//线条渲染,每帧加一段
currentLR.positionCount++;
//设置划线的位置信息
currentLR.SetPosition(currentLR.positionCount - 1, (Vector2)Camera.main.ScreenToWorldPoint(Input.mousePosition));
//碰撞器
BoxCollider2D collider = new GameObject("BoxCollider2D").AddComponent<BoxCollider2D>();
collider.transform.parent = currentLR.transform;
//最新的位置点
latestPoint = (Vector2)Camera.main.ScreenToWorldPoint(Input.mousePosition);
//碰撞器的位置在两个位置的中间
collider.transform.position = (previousPoint + latestPoint) * 0.5f;
//根据两个位置点设置碰撞器的角度
float angle = Mathf.Atan2((latestPoint - previousPoint).y, (latestPoint - previousPoint).x) * Mathf.Rad2Deg;
collider.transform.eulerAngles = new Vector3(0, 0, angle);
//碰撞器的长宽分别是两个位置的距离,和线的宽度
collider.size = new Vector2(Vector2.Distance(latestPoint, previousPoint), width);
//更新数据
previousPoint = (Vector2)Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
}
else if(Input.GetMouseButtonUp(0))
{
if(currentLR.transform.childCount > 0)
{
//鼠标抬起后,如果划线成功,用useAutoMass设置重量
currentLR.gameObject.AddComponent<Rigidbody2D>().useAutoMass = true;
}
}
}
}
|