方块的滚动移动最大的难题便是与地面的碰撞,当旋转角度过多的时候会导致方块莫名的弹起,为了解决这个办法必须加入在每一次滚动过后对方块状态的重置。
代码如下
private void Update()
{
if (endRotate == true)
{
towards = new Vector3(0, 0, Input.GetAxisRaw("Vertical")) + new Vector3(Input.GetAxisRaw("Horizontal"), 0, 0);
tempPoint = towards * 0.5f * cubeHight + new Vector3(transform.position.x, 0, transform.position.z);//0.5是cube的长的一半
if (towards.x == 0) roateAxis = new Vector3(towards.z, 0, 0);
else roateAxis = new Vector3(0, 0, -towards.x);
}
if (towards != Vector3.zero)
{
endRotate = false;
angle = rotateSpeed * Time.deltaTime;
transform.RotateAround(tempPoint, roateAxis, angle);
totalAngle += angle;
if (totalAngle >= 90)
{
transform.position = towards * cubeHight + initalTrans;
transform.rotation = Quaternion.identity;
initalTrans = transform.position;
totalAngle = 0;
endRotate = true;
}
}
}
代码通过寻找位移方向的相同点,相较于其他的滚动方式缩减了代码量,避免了对四个方向的判断。
借鉴了该大大的代码:Unity制作滚动的方块_unity正方体滚动_小小姑娘很大的博客-CSDN博客