Unity中让UI界面根据鼠标位置摇晃代码

Unity让UI随鼠标位置摇晃的模板代码:

        Vector2 range = new Vector2(4f, 3f); // 定义一个二维向量
	Quaternion mStart;  //  四元数
	Vector2 mRot = Vector2.zero;//旋转
	// Use this for initialization
	void Start () {
		mStart = transform.localRotation;  // 获取当前组件的本地旋转四元数
	}

	private void TransformTrans () {
		Vector3 pos = Input.mousePosition;   //  获取鼠标位置
		float halfWidth = Screen.width * 0.5f;   // 相对原点x
		float halfHeight = Screen.height * 0.5f; // 相对原点y
		float x = Mathf.Clamp ((pos.x - halfWidth) / halfWidth, -1f, 1f);  // 返回一个【-1,1】的x值
		float y = Mathf.Clamp ((pos.y - halfHeight) / halfHeight, -1f, 1f); // 返回一个【-1,1】的x值
//基于浮点数t返回a到b之间的插值,t限制在0~1之间。当t = 0返回from,当t = 1 返回to。当t = 0.5 返回from和to的平均值
// Quaternion.Euler(new Vector3())  返回一个旋转角度,绕z轴旋转z度,绕x轴旋转x度,绕y轴旋转y度(像这样的顺序)。 
		mRot = Vector2.Lerp (mRot,new Vector2 (x, y), Time.deltaTime);  // 插值运算
		transform.localRotation = mStart * Quaternion.Euler (-mRot.x * range.x, mRot.y * range.y, 0f);
	}
}


猜你喜欢

转载自blog.csdn.net/yguoelect/article/details/72523105