大家在做unity旋转缩放功能时,有时会遇到一些问题,就是很多模型如果初始角度或者中心点不一样,或者所有模型并不是统一制作的时候,旋转物体就无法达到一致的效果,这时候旋转摄像机就可以解决这个问题,本章分别讨论这两种方式。
一,物体的旋转缩放
在新建的工程中,新建个Cube,然后挂上脚本CubeMove
using UnityEngine;
using System.Collections;
public class CubeMove : MonoBehaviour
{
//X轴转动角度范围
public float yMinLimit = -20;
public float yMaxLimit = 80;
//缩放大小范围
public float sMinLimit = 0.2f;
public float sMaxLimit = 2f;
private float m_x;
private float m_y;
private float scale = 1;
void Start()
{
}
void Update()
{
if (Input.GetMouseButton(0))
{
//鼠标点击拖拽范围
m_x -= Input.GetAxis("Mouse X") * Time.deltaTime * 250;
m_y += Input.GetAxis("Mouse Y") * Time.deltaTime * 200;
m_y = ClampAngle(m_y, yMinLimit, yMaxLimit);
//选择角度赋值
this.transform.rotation = Quaternion.Euler(m_y, m_x, 0);
}
//鼠标滚轮缩放
scale -= Input.mouseScrollDelta.y * 1f * Time.deltaTime;
scale = Mathf.Clamp(scale, sMinLimit, sMaxLimit);
this.transform.localScale = new Vector3(scale, scale, scale);
}
//角度限制
float ClampAngle(float angle, float min, float max)
{
if (angle < -360)
{
angle += 360;
}
if (angle > 360)
{
angle -= 360;
}
return Mathf.Clamp(angle, min, max);
}
}
在工程中运行即可
二,摄像机旋转缩放
把脚本CameraMove挂在摄像机上,然后把需要观看的Cube作为目标对象进行赋值
using UnityEngine;
using System.Collections;
public class CameraMove : MonoBehaviour
{
//主摄像机
public Camera cam;
//需要观看的物体
public GameObject targetObj;
public float sMinLimit = 1;
public float sMaxLimit = 10;
public float yMinLimit = -20f;
public float yMaxLimit = 80f;
public float m_x = 0.0f;
public float m_y = 0.0f;
float scale = 10.0f;
void Start ()
{
cam = Camera.main;
}
void Update ()
{
if (Input.GetMouseButton(0))
{
//鼠标点击拖拽范围
m_x += Input.GetAxis("Mouse X") * Time.deltaTime * 250;
m_y -= Input.GetAxis("Mouse Y") * Time.deltaTime * 200;
m_y = ClampAngle(m_y, yMinLimit, yMaxLimit);
//选择角度赋值
this.transform.rotation = Quaternion.Euler(m_y, m_x, 0);
}
//鼠标滚轮缩放
scale -= Input.mouseScrollDelta.y * 1f;
scale = Mathf.Clamp(scale, sMinLimit, sMaxLimit);
var rotation = Quaternion.Euler(m_y,m_x,0);
//摄像机移动的方向
var position = rotation * new Vector3(0,0,-scale) + targetObj.transform.position;
this.transform.position = position;
}
float ClampAngle(float angle, float min, float max)
{
if (angle < -360)
{
angle += 360;
}
if (angle > 360)
{
angle -= 360;
}
return Mathf.Clamp(angle, min, max);
}
}
在工程中运行即可
两种方法效果一样,如图
转载请注明出处:http://blog.csdn.net/gzw187327