游戏制作时,有时会有限制某些物体旋转角度的需求,可以使用以下代码进行限制,此方法为使用了Mathf.Clamp来返回最大值和最小值之间的值,使填入的值不超出解限,然后不断赋值物体给新的旋转坐标,下面为限制Y轴的示例。
LimitViewY(-0.4f,0.35f);
public void LimitViewY(float minView,float MaxView)
{
float rotationY = Mathf.Clamp(Player.transform.rotation.y, minView, MaxView);
Quaternion a = new Quaternion(Player.transform.rotation.x, rotationY, Player.transform.rotation.z, Player.transform.rotation.w);
Player.transform.rotation = a;
}
稍加修改可以限制其他轴,以Z轴为例:
LimitViewZ(-0.2f,0.2f);
public void LimitViewZ(float minView,float MaxView)
{
float rotationZ = Mathf.Clamp(Player.transform.rotation.z, minView, MaxView);
Quaternion a = new Quaternion( Player.transform.rotation.x, Player.transform.rotation.y , rotationZ, Player.transform.rotation.w);
Player.transform.rotation = a;
}
PS:在EasyTouch插件中限制摇杆旋转角度,在ETCAxis脚本当中,找到DoDirectAction方法,在其中限制即可:
public void DoDirectAction()
{
if (directTransform){
Vector3 localAxis = GetInfluencedAxis();
Player = GameObject.FindWithTag("Player");
switch (directAction){
case ETCAxis.DirectAction.Rotate:
LimitViewY(-0.4f,0.35f);
directTransform.Rotate( localAxis * axisSpeedValue, Space.World);
break;
case ETCAxis.DirectAction.RotateLocal:
LimitViewZ(-0.2f,0.2f);
directTransform.Rotate( -localAxis * axisSpeedValue,Space.Self);//改变轴向
break;
}



