C#代码实现:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public lcass GunManager:MonoBehaviour{
//枪体绕x轴上下旋转的范围幅度为60度
private float minXRotation=0;
private float maxXRotation=60;
//枪体绕y轴左右旋转的范围幅度120度
private float maxYRotation=0;
private float maxYRotation=120;
void Start(){
}
void Update(){
//获取输入设备(鼠标)(x,y)坐标位置与屏幕比值
float xPosPrecent =Input.mousePosition.x/Screen.width;
float yPosPrecent =Input.mousePosition.y/Screen.height;
//使用Mathf.Clamp方法限制枪体旋转角度
float xAngle=-Mathf.Clamp(yPosPrecent*maxXRotation,minXRotation,maxXRotation)+30;
float yAngle= Mathf.Clamp(xPosPrecent*maxYRotation,minYRotation,maxYRotation)-60;
//将旋转角度值赋给枪体
transform.eulerAngles=new Vector3(xAngle,yAngle,0);
}
}
详解:
Unity中限制轴向移动范围方法Mathf.Clamp
在游戏中,为了限制GameObject的某一轴向的移动不超过一定的范围,可以用Mathf.Clamp来解决
Mathf.Clamp(float value,float min,float max)
在 Mathf.Clamp 中传入三个参数:value,min,max
限制 value的值在min,max之间,如果value大于max,则返回max,如果value小于min,则返回min,否者返回value;
Unity 的五种旋转方式之一:eulerAngles(欧拉角)
欧拉角是针对GameObject的一个旋转角度值。
具体调试参考:
https://blog.csdn.net/zxy13826134783/article/details/79461816