Unity 移动端(android) 移动 缩放 旋转
首先判断 两次的位置大小 缩放代码如下
private Vector2 oldops1; private Vector2 oldops2; //比较两次的位置,大小,来进行放大还是缩小 bool isEnlargc(Vector2 op1, Vector2 op2, Vector2 np1, Vector2 np2) { float lcngth1 = Mathf.Sqrt((op1.x - op2.x) * (op1.x - op2.x) + (op1.y - op2.y) * (op1.y - op2.y)); float lcngth2 = Mathf.Sqrt((np1.x - np2.x) * (np1.x - np2.x) + (np1.y - np2.y) * (np1.y - np2.y)); if (lcngth1 < lcngth2) { return true; } else { return false; } }
void Update(){ //判断两根手指在屏幕上移动并且不再UI上 if (Input.touchCount >1 && !EventSystem.current.IsPointerOverGameObject()) { if (Input.GetTouch(0).phase == TouchPhase.Moved || Input.GetTouch(1).phase == TouchPhase.Moved) { Vector2 tempos1 = Input.GetTouch(0).position; Vector2 tempos2 = Input.GetTouch(1).position; if (isEnlargc(oldops1, oldops2, tempos1, tempos2)) { //放大 float oldScale = lubansuoobj.transform.localPosition .z; float newScale = oldScale +1.025f; if (lubansuoobj.transform.localPosition.z <-18f) { lubansuoobj.transform.localPosition = new Vector3(0, 0, newScale); } } else { //缩小 float oldScale = lubansuoobj.transform.localPosition.z; float newScale = oldScale -1.025f; if (lubansuoobj.transform.localPosition.z >-40f) { lubansuoobj.transform.localPosition = new Vector3(0, 0, newScale); } } oldops1 = tempos1; oldops2 = tempos2; } } }
移动 旋转代码如下
float x, y; float Speed = 5; void Update() { //当前是否有任何鼠标按钮或键被按住 if (Input.anyKey) { //当只有一次触摸 if (Input.touchCount == 1) { //触摸类型,滑动 if (Input.GetTouch(0).phase == TouchPhase.Moved) { //移动拖拽 //获取x轴 x = Input.GetAxis("Mouse X") * Speed; //获取y轴 y = Input.GetAxis("Mouse Y") * Speed; this.transform.Translate(-x, y, 0);//*Time.deltaTime //旋转 ////获取x轴 //x = Input.GetAxis("Mouse X") * xSpeed; ////获取y轴 //y = Input.GetAxis("Mouse Y") * ySpeed; ////对模型进行上下左右旋转 Space.World世界坐标系,Space.Self 自身坐标系 //model.transform.Rotate(Vector3.up * x * Time.deltaTime, Space.World); //model.transform.Rotate(Vector3.left * -y * Time.deltaTime, Space.World); } } } }
加入利用插值旋转,(亲测可用)
float x, y; void Start(){ x = transform.eulerAngles.y; y = transform.eulerAngles.x; } void Update() { // 判断触摸数量为单点触摸 if (Input.touchCount == 1) { if (Input.GetTouch(0).phase == TouchPhase.Moved) { x += Input.GetAxis("Mouse X") * 5* 0.02f ; y -= Input.GetAxis("Mouse Y") * 5* 0.02f ; y = ClampAngle(y, -90, 90); Quaternion rotion = Quaternion.Euler(y, x, 0); transform.rotation = Quaternion.Lerp(transform.rotation, rotion, Time.deltaTime * 3); } } } //角度限制 static float ClampAngle(float angle, float min, float max) { if (angle < -90) angle = -90; if (angle > 90) angle = 90; return Mathf.Clamp(angle, min, max); }
这次就是这么多,以后会继续补充,感谢大家观看