0
\$\begingroup\$

Even if I set the value 1 on the y only on the spinAxis variable and leave both x and z 0 it will spin also on the x and z.

How can I make the objectToSpin to spin only on the y axis ?

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

public class MissleLauncherRotation : MonoBehaviour
{
    public GameObject objectToSpin;
    public Vector3 spinAxis;
    public float timeToSpin = 5f;
    public float spinSpeed = 20f;
    public bool randomSpin = false;

    private void Start()
    {
        StartCoroutine("Spin");
    }

    private void Update()
    {

    }

    IEnumerator Spin()
    {
        float spinTimer;
        while (true)
        {
            if (randomSpin == true)
            {
                spinAxis = Random.onUnitSphere;
            }

            spinTimer = timeToSpin;
            while (spinTimer > 0f)
            {
                objectToSpin.transform.Rotate(spinAxis, Time.deltaTime * spinSpeed);
                spinTimer -= Time.deltaTime;
                yield return null;
            }
        }
    }
}
\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

I would move the spinning from an own coroutine to Update (because you want to do it every frame), but then put the regular change of the spin vector to an own coroutine (because that's what you want to do every n seconds).

public class MissleLauncherRotation : MonoBehaviour
{
    public GameObject objectToSpin;
    public float timeToSpin = 0.5f;
    public float spinSpeed;

    private Vector3 spinVector;

    private void Start()
    {
        StartCoroutine("ChangeSpin");
    }

    private void Update()
    {
         objectToSpin.transform.Rotate(spinVector * Time.deltaTime);
    }

    IEnumerator ChangeSpin()
    {
        while (true)
        {
           if (Random.value < 0.5f) {
               spinVector = new Vector3(0f, spinSpeed, 0f);
           } else {
               spinVector = new Vector3(0f, -spinSpeed, 0f);
           }
           yield return new WaitForSeconds(timeToSpin);    
        }
    }
}

This code has a 50% chance every timeToSpin seconds to either switch direction or keep it. I assume that's what you meant with "change direction randomly every x seconds".

\$\endgroup\$
0
\$\begingroup\$

If you want to rotate around Y, then rotate around Y, not some axis that may or may not be aligned to Y. I don't know what exactly you mean by "randomly" but only on the Y axis. I assume you mean it sometimes speeds clockwise and sometimes counter-clockwise, randomly:

if (Random.value < 0.5f) {
    objectToSpin.transform.Rotate(Vector3.up, spinSpeed * Time.deltaTime);
} else {
    objectToSpin.transform.Rotate(Vector3.down, spinSpeed * Time.deltaTime);
}
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .