Обновить положение камеры с помощью клавиши со стрелкой вправо - PullRequest
0 голосов
/ 12 декабря 2018

Здравствуйте, в приведенном ниже коде я обновляю положение моей камеры с помощью кнопок пользовательского интерфейса, которые работают нормально, я хочу сделать тот же процесс, но нажимая клавишу со стрелкой вправо, как если бы я нажимал клавишу со стрелкой вправо, камера изменит свое положение на точкуА затем останавливается там, и когда я снова нажимаю ту же клавишу со стрелкой, камера изменит свое положение на точку B, и, как в коде, у меня есть другая функция, которая будет вызываться на другой кнопке пользовательского интерфейса, так что спасибо, вот мой код

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class cam : MonoBehaviour
{
    [Header("Locations where camera will update its position step by step")]
    public Transform handleview;
    public Transform needle1view;
    public Transform wallview;
    public Transform handletwoview;
    public Transform needle2view;
    public Transform switchview;
    public Transform lastswitchview;

    public GameObject Animatebtn;
    Animator animatebtnanim;

    [Header("UI Buttons")]
    public GameObject inspectionbtn;
    public GameObject animatebtn;
    public GameObject step2btn;
    public GameObject step3btn;
    public GameObject step4btn;
    public GameObject step5btn;
    public GameObject step6btn;
    public GameObject step7btn;

    [Header("Inspection Views")]
    public Transform startview;
    public Transform handle1view;
    public Transform motorview;
    public Transform handle2view;

    [Header("Move Boolean")]
    public bool move = false;

    [Header("Speed At Which Cam Moves")]
    public float speed;

    [Header("Current View/position Of Camera")]
    Transform currentVIEW;

    [Header("Current Angel Of Camera")]
    Vector3 currentangel;

    [Header("FieldofView of Camera ")]
    public float camFieldOFview = 24f;

    public int track = 0;

    // Use this for initialization
    void Start()
    {
        Camera.main.fieldOfView = camFieldOFview;
        animatebtnanim = Animatebtn.GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        if (move)
        {
            //float step = speed * Time.deltaTime;
            //transform.position = Vector3.MoveTowards(transform.position, currentVIEW.position, step);
            transform.position = Vector3.Lerp(transform.position, currentVIEW.position, Time.deltaTime * speed);
            currentangel = new Vector3(Mathf.LerpAngle(transform.rotation.eulerAngles.x, currentVIEW.transform.rotation.eulerAngles.x, Time.deltaTime * speed),
                Mathf.LerpAngle(transform.rotation.eulerAngles.y, currentVIEW.transform.rotation.eulerAngles.y, Time.deltaTime * speed),
                Mathf.LerpAngle(transform.rotation.eulerAngles.z, currentVIEW.transform.rotation.eulerAngles.z, Time.deltaTime * speed));

            transform.eulerAngles = currentangel;
        }

        //if (Input.GetKey(KeyCode.RightArrow))
        //{
        //    if (track == 7)
        //        track = 1;
        //    if (track == 1)
        //    {
        //        moveTOstartVIEW();
        //        move = true;
        //    }
        //    else if (track == 2)
        //    {
        //        moveTOhandleONEview();
        //        move = true;
        //    }
        //    track += 1;

        //}

    }
    // this function will lerp camera to startview location
    public void moveTOstartVIEW()
    {
        currentVIEW = startview;
        move = true;
    }

    public void moveTOhandleONEview()
    {
        currentVIEW = handle1view;
        move = true;
        animatebtnanim.SetBool("start", true);
        animatebtnanim.SetBool("move", false);
    }

    public void moveTOmotorview()
    {
        currentVIEW = motorview;

        move = true;
    }


    public void moveTOhandleTWOview()
    {
        currentVIEW = handle2view;
        move = true;
    }

    public void Handleview()
    {
        currentVIEW = handleview;
        inspectionbtn.SetActive(false);
        animatebtn.SetActive(false);
        move = true;
    }

    public void Needleoneview()
    {
        currentVIEW = needle1view;
        step2btn.SetActive(false);
        move = true;
    }

    public void Wallview()
    {
        currentVIEW = wallview;
        move = true;
        step3btn.SetActive(false);
    }

    public void Handletwoview()
    {
        currentVIEW = handletwoview;
        move = true;
        step4btn.SetActive(false);
    }

    public void Needletwoview()
    {
        currentVIEW = needle2view;
        move = true;
        step5btn.SetActive(false);
    }

    public void Switchview()
    {
        currentVIEW = switchview;
        move = true;
        step6btn.SetActive(false);
    }

    public void lastSwitchview()
    {
        currentVIEW = lastswitchview;
        move = true;
        step7btn.SetActive(false);
    }
}

1 Ответ

0 голосов
/ 12 декабря 2018

Как я понял, у вас есть обычный компонент UI.Button, и теперь вы хотите сделать то же самое с определенной клавишей на клавиатуре, что и эта кнопка в onClick.

Решение 1. Расширение кнопки

Я бы просто вызвал событие Button onClick после получения определенного KeyCode, поместив следующий компонент рядом с компонентом Button на вашей кнопке.объекты ( не на камере )

using UnityEngine;

// make sure you are not accidentely using 
// UnityEngine.Experimental.UIElements.Button
using UnityEngine.UI;

[RequireComponent(typeof(Button))]
public class KeyboardButton : MonoBehaviour
{
    // Which key should this Button react to?
    // Select this in the inspector for each Button
    public KeyCode ReactToKey;
    private Button _button;

    private void Awake()
    {
        _button = GetComponent<Button>();
    }

    // Wait for the defined key
    private void Update()
    {
        // If key not pressed do nothing
        if (!Input.GetKeyDown(ReactToKey)) return;

        // This simply tells the button to execute it's onClick event
        // So it does exactly the same as if you would have clicked it in the UI
        _button.onClick.Invoke();
    }
}

Решение 2. Замена кнопки

В качестве альтернативы, если вы больше не хотите использовать ButtonВ любом случае вы можете добавить свой собственный UnityEvent , например, OnPress к вышеуказанному сценарию вместо

using UnityEngine;
using UnityEngine.Events;

public class KeyboardButton : MonoBehaviour
{
    // Which key should this Button react to?
    // Select this in the inspector for each Button
    public KeyCode ReactToKey;

    // reference the target methods here just as 
    // you would do with the Button's onClick
    public UnityEvent OnPress;

    // Wait for the defined key
    private void Update()
    {
        // If key not pressed do nothing
        if (!Input.GetKeyDown(ReactToKey)) return;

        OnPress.Invoke();
    }
}
...