我使用下面的脚本通过鼠标移动平滑地移动一个对象(在X轴和Z轴上),它在世界轴上工作得很好,我的意思是当对象的旋转是(0,0,0)。
但是,我怎样才能使对象在它的本地轴上移动(我的意思是,当它的X轴旋转为-20时,它的Z轴移动应该是渐进式的)?
脚本。
private Vector3 screenPoint;
private Vector3 offset;
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown(0) || Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
screenPoint = Camera.main.WorldToScreenPoint(transform.position);
offset = transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
}
if (Input.GetMouseButton(0) && !Input.GetMouseButtonDown(0) || Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved)
{
Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
Vector3 curPosition = new Vector3((Camera.main.ScreenToWorldPoint(curScreenPoint).x + offset.x), 2, (Camera.main.ScreenToWorldPoint(curScreenPoint).z + offset.z));
float newX = Mathf.Clamp(curPosition.x, -3f, 3f);
float newZ = Mathf.Clamp(curPosition.z, -6f, 1.5f);
transform.position = Vector3.Lerp(transform.position, new Vector3(newX, transform.position.y, newZ), 10 * Time.deltaTime);
}
}
Okey我找到了答案,而且很简单。