【发布时间】:2018-11-03 02:58:31
【问题描述】:
我从这里得到了一些代码: https://answers.unity.com/questions/34317/rotate-object-with-mouse-cursor-that-slows-down-on.html
private float rotationSpeed = 10.0F;
private float lerpSpeed = 1.0F;
private Vector3 theSpeed;
private Vector3 avgSpeed;
private bool isDragging = false;
private Vector3 targetSpeedX;
void OnMouseDown() {
isDragging = true;
}
void Update() {
if (Input.GetMouseButton(0) && isDragging) {
theSpeed = new Vector3(-Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"), 0.0F);
avgSpeed = Vector3.Lerp(avgSpeed, theSpeed, Time.deltaTime * 5);
} else {
if (isDragging) {
theSpeed = avgSpeed;
isDragging = false;
}
float i = Time.deltaTime * lerpSpeed;
theSpeed = Vector3.Lerp(theSpeed, Vector3.zero, i);
}
transform.Rotate(Camera.main.transform.up * theSpeed.x * rotationSpeed, Space.World);
transform.Rotate(Camera.main.transform.right * theSpeed.y * rotationSpeed, Space.World);
}
此代码通过鼠标单击和拖动来旋转对象,单击后,对象会缓慢停止。我现在想要这个功能在手机上。这是我的移动版代码:
// Update is called once per frame
public void Update() {
// Track a single touch as a direction control.
if (Input.touchCount > 0) {
Touch touch = Input.GetTouch(0);
// Handle finger movements based on touch phase.
switch (touch.phase) {
// Record initial touch position.
case TouchPhase.Began:
startPos = touch.position;
directionChosen = false;
break;
// Determine direction by comparing the current touch position with the initial one.
case TouchPhase.Moved:
direction = touch.position - startPos;
break;
// Report that a direction has been chosen when the finger is lifted.
case TouchPhase.Ended:
directionChosen = true;
stopSlowly = true;
Debug.Log("end");
break;
}
}
if (directionChosen) {
// Something that uses the chosen direction...
theSpeed = new Vector3(-direction.x, direction.y, 0.0F);
avgSpeed = Vector3.Lerp(avgSpeed, theSpeed, Time.deltaTime * 5);
} else {
if (stopSlowly) {
Debug.Log("TESTOUTPUT");
theSpeed = avgSpeed;
isDragging = false;
}
float i = Time.deltaTime * lerpSpeed;
theSpeed = Vector3.Lerp(theSpeed, Vector3.zero, i);
}
transform.Rotate(camera.transform.up * theSpeed.x * rotationSpeed, Space.World);
transform.Rotate(camera.transform.right * theSpeed.y * rotationSpeed, Space.World);
这里有一些变量,我使用 Vector2 变量作为 startPos 和方向:
private float rotationSpeed = 1f;
private float lerpSpeed = 1.0F;
private Vector3 theSpeed;
private Vector3 avgSpeed;
private bool isDragging = false;
private Vector3 targetSpeedX;
public Vector2 startPos;
public Vector2 direction;
public bool directionChosen;
public bool stopSlowly;
现在,如果我按下播放键并旋转手机上的对象,它会旋转,但不会自行结束。它的旋转速度也非常快。当我一次触摸对象时,它立即停止。 请有人能告诉我我的代码到底有什么问题。我的目标只是旋转,从触摸输入初始化,然后缓慢结束直到静止。
谢谢
【问题讨论】: