[c#]代码库
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class VectorDotCross_001 : MonoBehaviour
{
public Image ImageMoveUI; //要移动的图片,也可以是gameobject
private Vector3 Vector3MousePosition; //当前鼠标的坐标
private Vector3 Vector3point; //图片指向鼠标指针方向
private bool BoolMoveflag = false; //图片移动判断
void Update()
{
if (Input.GetMouseButtonDown(0))
{
ReRotateMethod(); //旋转物体
}
if (BoolMoveflag)
{
ReMoveMethod(); //图片进行移动
}
}
void ReRotateMethod()
{
BoolMoveflag = true;
//获取摄像机指向鼠标点击方向的向量
Vector3MousePosition = Input.mousePosition - Camera.main.transform.position;
//获取图片指向鼠标点击方向的向量
Vector3point = Vector3MousePosition - ImageMoveUI.transform.position;
//然后计算图片到鼠标方向的夹角
//点乘的结果是两个向量的大小相乘在乘其Cos值
float floatCurretRotate = Vector3.Dot(ImageMoveUI.transform.up.normalized, Vector3point.normalized);
float Rotate = Mathf.Acos(floatCurretRotate) * Mathf.Rad2Deg;
//由于计算的夹角不会大于180度,所以需要判断旋转方向
//也就是说当前鼠标的位置是否和图片上方处于同一侧,这里使用叉乘来判断
//两个向量叉乘得到一个新的向量,该向量垂直于原来的两个向量,其长度对于其长度相乘的正弦值
Vector3 VecCross = Vector3.Cross(ImageMoveUI.transform.up, Vector3point);
//我们判断叉乘得到的向量的Z轴正负,来让图片是否是逆时针转还是顺时针转
Vector3 point;
if (VecCross.z < 0)
{
point = Vector3.back;
}
else
{
point = Vector3.forward;
}
//让图片进行旋转
if (Rotate > 1f)
{
ImageMoveUI.transform.RotateAround(ImageMoveUI.transform.position, point, Rotate);
}
}
private void ReMoveMethod()
{
//判断距离
if (Vector3.Distance(ImageMoveUI.transform.position, Vector3MousePosition) > 3f)
{
ImageMoveUI.transform.position = ImageMoveUI.transform.position + Vector3point.normalized * 2f;
}
else
{
BoolMoveflag = false;
}
}
}