Unity 2D如何实现仅点击的立方体旋转而非所有生成立方体同时旋转
问题核心原因
- 该脚本挂载在所有实例化的立方体上,每个立方体的
Update方法都会独立响应鼠标点击检测 - 只要射线命中任意一个带
colourBox标签的立方体,所有未被noRotation锁定的立方体都会触发自身的旋转逻辑,因此出现全部同步旋转的问题 - 之前添加的布尔变量未生效,是因为没有在旋转过程中修改
noRotation的状态,也没有限制仅命中自身时才触发旋转
修复逻辑
- 射线检测命中物体后,额外判断命中的物体是否为当前脚本挂载的立方体,仅命中自身时才执行旋转
- 旋转开始时将
noRotation设为true,避免旋转过程中重复触发,旋转完成后重置为false - 优化旋转角度判断逻辑,避免角度超过360°时的判定异常
修改后代码
{ public int rotationDirection = -1; //-1 for clockwise public int rotationStep = 5; //Should be less than 90 public bool noRotation; // public GameObject cubeBox; private Vector3 currentRotation, targetRotation; // Update is called once per frame void Update() { if (Input.GetMouseButtonDown(0)) { RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero); // 新增判断:命中的物体必须是当前脚本挂载的立方体本身 if (hit.collider != null && hit.collider.tag == "colourBox" && noRotation == false && hit.collider.gameObject == gameObject) { Debug.Log("object clicked: " + hit.collider.tag); RotateCube(); } } } void RotateCube() { // 旋转开始前锁定状态,防止重复点击触发 noRotation = true; currentRotation = gameObject.transform.eulerAngles; targetRotation.z = Mathf.Repeat(currentRotation.z + (90 * rotationDirection), 360); StartCoroutine(objectRotationAnimation()); } IEnumerator objectRotationAnimation() { currentRotation.z = Mathf.Repeat(currentRotation.z + (rotationStep * rotationDirection), 360); gameObject.transform.eulerAngles = currentRotation; yield return null; // 优化角度判断逻辑,适配正/反向旋转的判定 bool isRotating = rotationDirection < 0 ? currentRotation.z > targetRotation.z : currentRotation.z < targetRotation.z; if (isRotating) { StartCoroutine(objectRotationAnimation()); } else { // 旋转完成,解除状态锁定 noRotation = false; } } }
内容的提问来源于stack exchange,提问作者Edgar
相关产品推荐
相关产品推荐

