写一段unity中模型拆装的代码。需求:声明一个已有的坐标轴模型,并且声明模型的三个轴。功能:鼠标点击模型的子零件,会为零件添加Outline…
- User
写一段unity中模型拆装的代码。需求:声明一个已有的坐标轴模型,并且声明模型的三个轴。功能:鼠标点击模型的子零件,会为零件添加Outline Effect插件中的Outline组件,还会将坐标轴显示在被点击零件的上方,并且坐标轴模型不会在功能打开期间消失,只会随着功能的关闭而隐藏,随着点击不同的模型零部件而出现在它们上方,一次只能进行一个零部件的点击;鼠标左键点击拖拽坐标轴模型的三个坐标轴带动被点击零部件进行三个方向上的位移,一次只能够拖拽移动一个方向。
- Assistant
- User
/声明坐标轴模型 public GameObject axisModel;
//声明坐标轴 private GameObject xAxis; private GameObject yAxis; private GameObject zAxis;
//声明当前被点击的零件 private GameObject selectedPart;
void Update() { if (Input.GetMouseButtonDown(0)) //鼠标左键点击 { //从鼠标位置发射一条射线 Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit; //定义射线碰撞的信息
if (Physics.Raycast(ray, out hit)) //如果射线有碰撞到物体 { selectedPart = hit.collider.gameObject; //记录下被点击的零件
//在被点击零件上添加Outline组件 Outline outline = selectedPart.AddComponent(); outline.OutlineMode = Outline.Mode.OutlineVisible; outline.OutlineColor = Color.white; outline.OutlineWidth = 5f;
- Assistant
public bool isTransforming = true; //默认开启拆装功能
void Update() { if (isTransforming) //仅当功能开启时才执行以下代码 { //代码不变 } }
//添加一个Public方法,用于手动开启或关闭拆装功能 public void ToggleTransforming(bool isOn) { isTransforming = isOn; }
- User
- Assistant
- User
//生成坐标轴并设置位置 xAxis = Instantiate(axisModel, selectedPart.transform.position, Quaternion.identity); yAxis = Instantiate(axisModel, selectedPart.transform.position, Quaternion.Euler(0, 0, 90)); zAxis = Instantiate(axisModel, selectedPart.transform.position, Quaternion.Euler(0, 90, 0));将这段代码改为将坐标轴移动到被选中模型子零件的上方
- Assistant
//获取被选中模型的Bounds Bounds bounds = selectedPart.GetComponent().bounds;
//生成坐标轴并设置位置 xAxis = Instantiate(axisModel, bounds.center + new Vector3(bounds.extents.x, 0, 0), Quaternion.identity); yAxis = Instantiate(axisModel, bounds.center + new Vector3(0, bounds.extents.y, 0), Quaternion.Euler(0, 0, 90)); zAxis = Instantiate(axisModel, bounds.center + new Vector3(0, 0,