Как повернуть Объект с помощью сенсорного ввода и медленно остановить его после этого в Unity? - PullRequest
0 голосов
/ 27 октября 2018

Я получил некоторый код отсюда: 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 и ​​direction:

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;

Теперь, если я нажимаю play и поворачиваюОбъект на моем телефоне, он вращается, но не заканчивается сам по себе.Он также вращается очень быстро.Когда я коснулся Объекта один раз, он немедленно останавливается.Пожалуйста, может кто-нибудь сказать мне, что именно не так с моим кодом.Моя цель - просто вращение, инициализируемое от сенсорного ввода и медленного окончания до его остановки.

Спасибо

Ответы [ 2 ]

0 голосов
/ 02 ноября 2018

Сейчас я использую некоторые физики, чтобы решить эту проблему:

// React on User Touch Input -> Rotate gameObject
        if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved) {
            // Get movement of the finger since last frame
            Vector2 touchDeltaPosition = Input.GetTouch(0).deltaPosition;

            // Add Torque to gameObject
            rb.AddTorque(camera.transform.up * -touchDeltaPosition.x/* * optionalForce*/);
            rb.AddTorque(camera.transform.right * touchDeltaPosition.y/* * optionalForce*/);
        } else if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Ended) {
            // throw anker, stop rotating slowly
            rb.angularDrag = 0.7f;
        }

Этот код предназначен для сенсорного ввода и вращает объект + медленно останавливает его.Вам нужно твердое тело на вашем объекте, который вы хотите вращать.Здесь его называют рб.камера моя основная камера.

0 голосов
/ 28 октября 2018

ваше состояние очень сбивает с толку. попробуйте что-то вроде этого

    // Handle finger movements based on touch phase.
    switch (touch.phase) {
        // Record initial touch position.
        case TouchPhase.Began:
            startPos = touch.position;
            break;

        // Determine direction by comparing the current touch position with the initial one.
        case TouchPhase.Moved:
            direction = touch.position - startPos;
            isDragging = true;
            break;

        // Report that a direction has been chosen when the finger is lifted.
        case TouchPhase.Ended:
            isDragging = false;
            stopSlowly = true;
            Debug.Log("end");
            break;
    }

if (isDragging) {
    // 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;
        stopSlowly = false;
    }
    float i = Time.deltaTime * lerpSpeed;
    theSpeed = Vector3.Lerp(theSpeed, Vector3.zero, i);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...