将需要缩放的模型添加碰撞体,我这里以cube代替。
新建一个脚本,命名为test.cs
添加如下代码
///
/// 当前点击到的物体
///
private GameObject curObj = null;
private Vector3 oldPos = Vector2.zero;
private Touch oldTouch1;
private Touch oldTouch2;
private void Update()
{
if (Input.GetMouseButtonDown(0)) {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo))
{
if (hitInfo.transform.CompareTag("furniture"))
{
curObj = hitInfo.collider.gameObject;
oldPos = Input.mousePosition;
}
}
}
if (Input.GetMouseButtonUp(0)) {
curObj = null;
}
if (curObj != null) {
CheckTouchRotate();
CheckTouchAdjustHeight();
CheckTouchAdjustScal();
}
}
///
/// 触摸控制旋转
///
void CheckTouchRotate() {
#if UNITY_EDITOR
float dis = Input.mousePosition.x - oldPos.x;
if (Mathf.Abs(dis) > 5.0f) {
curObj.transform.Rotate(0, -Input.GetAxis("Mouse X") * 500 * Time.deltaTime,0,Space.Self);
}
//oldPos = Input.mousePosition;
#elif UNITY_ANDROID || UNITY_IOS
if (Input.touchCount < 0)
{
return;
}
if (Input.touchCount == 1)
{
if (Input.touches[0].phase == TouchPhase.Began)
oldPos = Input.touches[0].position;
if (Input.touches[0].phase == TouchPhase.Moved)
{
Vector2 deltaPos = Input.touches[0].deltaPosition;
float dis = Input.touches[0].position.x - oldPos.x;
if (Mathf.Abs(dis) > 5)
{
curObj.transform.Rotate(0, -deltaPos.x * 100 * Time.deltaTime, 0, Space.Self);
}
}
}
#endif
}
///
/// 触摸调整高度
///
void CheckTouchAdjustHeight() {
#if UNITY_EDITOR
float dis = Input.mousePosition.y - oldPos.y;
if (Mathf.Abs(dis) > 5.0f)
{
curObj.transform.Translate(0, Input.GetAxis("Mouse Y") * 30 * Time.deltaTime, 0);
}
oldPos = Input.mousePosition;
#elif UNITY_ANDROID || UNITY_IOS
if (Input.touchCount < 0)
{
return;
}
if (Input.touchCount == 1)
{
if (Input.touches[0].phase == TouchPhase.Began)
oldPos = Input.touches[0].position;
if (Input.touches[0].phase == TouchPhase.Moved)
{
Vector2 deltaPos = Input.touches[0].deltaPosition;
float dis = Input.touches[0].position.y - oldPos.y;
if (Mathf.Abs(dis) > 5)
{
curObj.transform.Translate(0, deltaPos.y * 30 * Time.deltaTime, 0);
}
}
}
#endif
}
///
/// 触摸调整缩放
///
void CheckTouchAdjustScal() {
#if UNITY_EDITOR
float scalFactor = Input.GetAxis("Mouse ScrollWheel");
curObj.transform.localScale += new Vector3(scalFactor, scalFactor, scalFactor);
#elif UNITY_ANDROID || UNITY_IOS
if (Input.touchCount <= 0) {
return;
}
if (Input.touchCount == 2) {
Touch newTouch1 = Input.GetTouch(0);
Touch newTouch2 = Input.GetTouch(1);
if (newTouch2.phase == TouchPhase.Began) {
oldTouch1 = newTouch1;
oldTouch2 = newTouch2;
return;
}
float oldDis = Vector2.Distance(oldTouch1.position, oldTouch2.position);
float newDis = Vector2.Distance(newTouch1.position, newTouch2.position);
float offsetDis = newDis - oldDis;
float scalFactor = offsetDis / 10.0f;
curObj.transform.localScale += new Vector3(scalFactor, scalFactor, scalFactor);
oldTouch1 = newTouch1;
oldTouch2 = newTouch2;
}
#endif
}
将这个脚本放在摄像机上即可。