Как заставить определенный префаб вращаться при нажатии кнопки? - PullRequest
0 голосов
/ 12 декабря 2018

Я разрабатываю игру, и в текущей сцене, которую я разрабатываю, около 100 префабов.enter image description here

Рисунок выше показывает, как обычно выглядит объект.

То, что я хочу сделать, - это когда я нажимаю красную кнопку, я хочу, чтобы модель автомобиля посередине вращалась.С debug.Log я понял, что когда я нажимаю F (используйте), я хочу, чтобы этот конкретный объект вращался.

То, что я до сих пор делал, с точки зрения кода:

        private void SearchForObject()
        {
            if (!m_ItemCoolDown)
            {
                if (m_Target != null)
                {
                    if (m_Target.tag == m_InteractWithObjectsTag)
                    {
                        if (m_WeaponUI != null)
                            m_WeaponUI.ShowPickupMessage("PRESS <color=#FF9200FF>" + m_UseKey + "</color> TO INTERACT WITH THE OBJECT");

                        if (InputManager.GetButtonDown("Use"))
                        {


                            Debug.Log("Button pressed");
                        }
                    }
                }
            }
        }

Но как я могу заставить код понять, что я хочу, чтобы этот объект вращался?

есть еще около 100 таких объектов, поэтому когда я подхожу к ним и нажимаю F, я хочу, чтобы они тоже вращались ..

Я думал о том, чтобы создать сценарий, иприкрепите его к кнопке и прикрепите к нему модель автомобиля, примерно так: enter image description here

, и когда я нажимаю F, я хочу, чтобы скрипт перешел к этому другому сценарию,возьмите конкретную модель и затем поверните.Но я не уверен, как это сделать, у кого-нибудь есть идеи?

спасибо

1 Ответ

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

Я предполагаю, что ваш скрипт в основном делает то, что должен.

Я бы взял то, что вы уже упомянули, и позволил самой кнопке сохранить ссылку на свой целевой объект и обработать поворот.

Длядля поворота вы можете использовать простую сопрограмму :

public class ButtonScript : MonoBehaviour
{
    // The object that should rotate
    public Transform ObjectToTransform;

    // How long it should take to rotate in seconds
    public float RotationDuration = 1;

    // flag for making sure you can start rotating only if not already rotating
    private bool _isRotating;

    public void StartRotating()
    {
        // if already rotating do nothing
        if(_isRotating) return;

        StartCoroutine(Rotate());
    }

    // Rotates the ObjectToTransform 360° around its world up vector
    // in RotationDuration seconds
    private IEnumerator Rotate()
    {
        // set the flag so rotation can not be started multiple times
        _isRotating= true;

        // store the original rotation the target object currently has
        var initialRotation = ObjectToTransform.rotation;

        // we can already calculate the rotation speed in angles / second
        var rotationspeed = 360 / RotationDuration;

        // Rotate the object until the given duration is reached
        var timePassed = 0;    
        while(timePassed < RotationDuration)
        {
            // Time.deltaTime gives you the time passed since the last frame in seconds 
            // So every frame turn the object around world Y axis a little
            ObjectToTransform.Rotate(0, rotationspeed  * Time.deltaTime, 0, Space.World);

            // add the time passed since the last frame to the timePassed            
            timePassed += Time.deltaTime;

            // yield makes the Courutine interupt here so the frame can be rendered 
            // but the it "remembers" at which point it left
            // so in the next frame it goes on executing the code from the next line
            yield return null;
        }

        // Just to be sure we end with a clean rotation reset to the initial rotation in the end
        // since +360°  
        ObjectToTransform.rotation = initialRotation;

        // reset the flag so rotation can be started again
        _isRotating= false;
    }
}

Так что я также предполагаю, что m_Target - это конкретная «кнопка», которую вы хотите нажать, правее, чем все, что осталось сейчасэто запустить сопрограмму на этой кнопке:

private void SearchForObject()
{
    if (!m_ItemCoolDown)
    {
        if (m_Target != null)
        {
            if (m_Target.tag == m_InteractWithObjectsTag)
            {
                if (m_WeaponUI != null)
                    m_WeaponUI.ShowPickupMessage("PRESS <color=#FF9200FF>" + m_UseKey + "</color> TO INTERACT WITH THE OBJECT");

                if (InputManager.GetButtonDown("Use"))
                {
                    Debug.Log("Button pressed");

                    // if m_Target is not the button you'll have to get a reference
                    // to the button somehow
                    m_Target.GetComponent<ButtonScript>.StartRotating();
                }
            }
        }
    }
}

и установить ссылку targetObject в инспекторе на объект, который должен быть повернут.Или, если это префаб, который инициируется, вы можете сделать что-то вроде

var obj = Initialize(prefab /*, parameters if you have some*/);
// ButtonObject is the reference to your button GameObject
ButtonObject.GetComponent<ButtonScript>().targetObject = obj.transform;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...