【发布时间】:2021-10-31 21:48:28
【问题描述】:
所以我正在实例化立方体,我想旋转一个单击的立方体,但是当我单击立方体时,所有实例化的立方体同时旋转,我一直尝试使用布尔值但没有成功。任何帮助,将不胜感激。 UNITY 2D
{
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)
{
Debug.Log("object clicked: " + hit.collider.tag);
RotateCube();
}
}
}
void RotateCube()
{
currentRotation = gameObject.transform.eulerAngles;
targetRotation.z = (currentRotation.z + (90 * rotationDirection));
StartCoroutine(objectRotationAnimation());
}
IEnumerator objectRotationAnimation()
{
currentRotation.z += (rotationStep * rotationDirection);
gameObject.transform.eulerAngles = currentRotation;
yield return new WaitForSeconds(0);
if (((int)currentRotation.z > (int)targetRotation.z && rotationDirection < 0))
{
StartCoroutine(objectRotationAnimation());
}
}
}
【问题讨论】:
-
条件判断一个立方体是否被点击,但需要判断当前立方体是否被点击。我不知道团结,但也许
if (hit.collider != null && hit.collider.tag == "colourBox" && hit.collider.attachedRigidbody == this && noRotation == false). -
我将光线投射更改为 OnMouseDown 并解决了问题。但是我仍然想知道如果我使用上面的代码会有什么解决方案!
private void OnMouseDown() { RotateCube(); }