多个物体,在每个物体上都挂一个脚本;
在物体后面放个image Body,设透明,用来判断鼠标点下时,点到的是哪个物体,六个物体,六个Image;
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class Book2xuanzhuan : MonoBehaviour
{
public Image Body;//ui元素的本体, panel等
public RectTransform CanvasRectangle; //image所在的画布
public float xSpeed = 250.0f;
public float ySpeed = 130.0f;
//限制旋转角度,物体绕x轴旋转限制,不能上下颠倒。
public float yMinLimit = -30;
public float yMaxLimit = 9000;
//物体的旋转角度
public float x = 0.0f;
public float y = 0.0f;
public GameObject Cake1;
Quaternion angels;
bool Cake;//判断点到的是哪个物体
void Start()
{
//初始化旋转角度,记录开始时物体的旋转角度。
angels = Cake1.transform.rotation;
x = angels.y;
y = angels.x;
Cake = false;
}
public void OnBeginDrag(BaseEventData baseEventData)
{
Cake = true;
}
public void OnDrag(BaseEventData baseEventData)
{
Cake = true;
x += Input.GetAxis("Mouse X") * xSpeed * 0.02f;
y += Input.GetAxis("Mouse Y") * ySpeed * 0.02f;
}
public void OnEndDrag(BaseEventData baseEventData)
{
Cake = false;
Cake1.transform.rotation = angels;
}
void Update()
{
}
void LateUpdate()
{
if (Cake)
{
y = Mathf.Clamp(y, yMinLimit, yMaxLimit);
Quaternion rotation = Quaternion.Euler(y, -x, 0);
Cake1.transform.rotation = rotation;
}
}
}