using UnityEngine; using cakeslice; // 使用 Outline 插件 public class MoxingControl :…
- User
using UnityEngine; using cakeslice; // 使用 Outline 插件
public class MoxingControl : MonoBehaviour { private Transform selectedPart = null; // 当前选中的零件 private Outline outline = null; // 选中零件的 Outline 组件 private Color selectedColor = Color.yellow; // 选中零件的颜色 private bool isControlEnabled = false; // 模型控制是否启用 private Animator animator; // Animator 组件 private bool animatorEnabled = true; // Animator 是否启用 public GameObject axisPrefab; // 坐标轴预制体
private GameObject axisObj; // 当前选中零件的坐标轴对象 private bool axisVisible = false; // 坐标轴是否可见
public void ToggleControlEnabled() { // 切换模型控制状态 isControlEnabled = !isControlEnabled; animator.enabled = !animator.enabled; }
private void Update() { animator = GetComponent(); if (!isControlEnabled) return; // 如果模型控制未启用,直接返回 if (Input.GetMouseButtonDown(0)) { // 鼠标左键点击选择零件 Transform clickedPart = GetClickedPart(transform); if (clickedPart != null) { // 如果点击到零件 if (selectedPart != null) { // 如果已有选中的零件 Destroy(outline); // 删除旧的 Outline 组件 if (selectedPart == clickedPart) { // 如果选中的是同一个零件 selectedPart = null; HideAxis(); return; } } selectedPart = clickedPart; // 选中新的零件 outline = selectedPart.gameObject.AddComponent(); // 添加新的 Outline 组件 // outline.OutlineColor = selectedColor; // 设置选中零件的颜色 // outline.OutlineWidth = 4; // 设置轮廓宽度
ShowAxis(selectedPart); // 显示坐标轴 } else if (selectedPart != null) { // 如果点击空白处,取消选中状态 Destroy(outline); selectedPart = null; HideAxis(); } } if (Input.GetMouseButton(0) && selectedPart != null) { // 鼠标左键拖动选中零件 float x = Input.GetAxis(“Mouse X”) / 10000f; float y = Input.GetAxis(“Mouse Y”) / 10000f; float z = Input.GetAxis(“Mouse ScrollWheel”) * 10f; Vector3 offset = new Vector3(x, y, z); selectedPart.position += selectedPart.transform.TransformDirection(offset); // 移动选中零件 } }
private Transform GetClickedPart(Transform parent) { // 获取鼠标点击的零件 Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(ray, out hit)) { Transform clickedPart = hit.transform; // 获取点击到的零件 if (IsDescendant(clickedPart, parent)) { // 如果是指定父物体的子物体 return clickedPart; } } return null; }
private bool IsDescendant(Transform child, Transform parent) { // 判断物体是否是指定父物体的子物体 foreach (Transform t in parent) { if (t == child) return true; if (IsDescendant(child, t)) return true; } return false; }
private void ShowAxis(Transform part) { if (axisObj != null) Destroy(axisObj); // 删除旧的坐标轴对象 axisObj = Instantiate(axisPrefab, part.position, part.rotation, part); // 创建新的坐标轴对象 axisVisible = true; }
private void HideAxis() { if (!axisVisible) return; // 如果坐标轴已经隐藏,直接返回 if (axisObj != null) Destroy(axisObj); // 删除坐标轴对象 axisVisible = false; } }修改代码:将坐标轴显示在被点击模型的上方0.2f处。请将完整代码写出
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.