零.具体问题:
2D游戏内实现鼠标拖拽大钟指针至正确位置且指针互不影响。
一.实现方法:
将指针分别设立新的Tag,使用鼠标射线碰撞判断是否接触到指针所在Tag同时将另一根指针所在图册设为可触碰范围外以实现功能。
二.具体步骤
1.将两个指针的父物体分别设立新的Tag并分别,并对父物体建立3D碰撞盒。
2.代码实现
public bool onDrag = false; //是否被拖拽
public float speed = 4f; //旋转速度
private float tempSpeed; //阻尼速度
private float axisX = 1; //鼠标沿水平方向移动的增量
private float axisY = 1; //鼠标沿竖直方向移动的增量
private float lengthXY;
private float axisZ = 0;
private int nums = 1;
//public int sceneNumst = 3;
//private float OffsetX = 1; //鼠标沿水平方向移动的增量
private float OffsetY = 1; //鼠标沿竖直方向移动的增量
public GameObject bigClock1;
public GameObject bigClock2;
public static int sceneNums = 3; //转换场景层数
float Rigid()
{
if (onDrag){
tempSpeed = speed;
}else{
tempSpeed = 10000000;
}
return tempSpeed;
}
public void MouseMove()//拖拽
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Debug.DrawRay(Input.mousePosition, ray.direction, Color.red, 5.0f);
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo))
{
GameObject gameObj = hitInfo.transform.gameObject;
if (gameObj.transform.tag == "bigClock1")
{
onDrag = true;
bigClock2.tag = "GameController";
axisX = Input.GetAxis("Mouse X");
axisY = Input.GetAxis("Mouse Y");
float square = axisX * axisX + axisY * axisY;//转换屏幕坐标至三维坐标
if (square > 1.0f)
{
float sca = 1.0f / Mathf.Sqrt(square);
axisX *= sca;
axisY *= sca;
}
else { axisZ = Mathf.Sqrt(1.0f - square); }//
if (lengthXY == 0f)
{
lengthXY = 1f;
}
bigClock1.transform.Rotate(new Vector3(0, 0, axisZ) * Rigid()/3, Space.World);
}
else if (gameObj.transform.tag == "bigClock2" )
{
onDrag = true;
bigClock1.tag = "GameController";
axisX = Input.GetAxis("Mouse X");
axisY = Input.GetAxis("Mouse Y");
float square = axisX * axisX + axisY * axisY;
if (square > 1.0f)
{
float sca = 1.0f / Mathf.Sqrt(square);
axisX *= sca;
axisY *= sca;
}
else { axisZ = Mathf.Sqrt(1.0f - square); }
if (lengthXY == 0f)
{
lengthXY = 1f;
}
bigClock2.transform.Rotate(new Vector3(0, 0, axisZ) * Rigid() / 3, Space.World);
}
}
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
axisX = 0f;
axisY = 0f;
bigClock1.tag = "bigClock1";
bigClock2.tag = "bigClock2";
}
if (Input.GetMouseButton(0))
{
nums = 1;
MouseMove();
}
}
}
3.注意事项:
(1).由于使用射线碰撞所以建立3D碰撞盒.
(2).在其他功能实现中使用了EventSystem所以应在Update中使用Input.GetMouseButtonDown(0)函数实现获取鼠标输入。
(3)因为鼠标输入时获取为屏幕坐标,应将屏幕坐标转换为三维坐标。由于本项目中获取的为向量,因为此代码只实现顺时针拖拽旋转
(4)为实现指针绕一点固定旋转,因此将此脚本挂在指针的父物体。