I’ve tried a few ways to rotate an object, but all of them snap rotate it, instead of doing it smoothly. here is current code.
public float speed;
public float turnSpeed;
public int turnDecider;
private float yRotation;
public float turnVariable1;
private float turnVariable2;
private float turnVariable3;
private float turnVariable4;
void Start()
{
InvokeRepeating(“RandomTurn”, 1.0f, 1.0f);
}
// Update is called once per frame
void Update()
{
transform.Translate(Vector3.left * speed * Time.deltaTime);
yRotation = transform.rotation.eulerAngles.y;
turnVariable1 = yRotation - 30;
turnVariable2 = yRotation - 60;
turnVariable3 = yRotation + 30;
turnVariable4 = yRotation + 60;
}
void RandomTurn()
{
turnDecider = Random.Range(0, 5);
if (turnDecider == 1)
{
transform.rotation = Quaternion.AngleAxis(30, Vector3.up);
}
if (turnDecider == 2)
{
transform.rotation = Quaternion.AngleAxis(60, Vector3.up);
}
if (turnDecider == 3)
{
transform.rotation = Quaternion.AngleAxis(30, Vector3.down);
}
if (turnDecider == 4)
{
transform.rotation = Quaternion.AngleAxis(60, Vector3.down);
}
}
anyway I can easily modify it to rotate smoothly?
This is the first thing I came up with. It seems to work the way you want. Your main problem is that you’re updating the rotation to the new rotation, every second, so there’s nothing to smooth it. Mine uses a randomizer function like yours, then stores the value in a class variable so that the Update function can access it. Update is run every frame, which means its where you need to put anything to do with smooth motion (along with making sure you’re using Time.deltaTime properly). Note that ‘rotationSpeed’ is in degrees/second.
private Quaternion targetRotation;
private float rotationSpeed = 45;
void Start()
{
InvokeRepeating("randomRotation", 1.0f, 1.0f);
}
void Update()
{
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
}
void randomRotation()
{
Quaternion rotation = new Quaternion();
switch (Random.Range(0, 4))
{
case 0:
rotation = Quaternion.AngleAxis(30, Vector3.up);
break;
case 1:
rotation = Quaternion.AngleAxis(60, Vector3.up);
break;
case 2:
rotation = Quaternion.AngleAxis(30, Vector3.down);
break;
case 3:
rotation = Quaternion.AngleAxis(60, Vector3.down);
break;
}
targetRotation = rotation;
}
Quaternion targetRot;
public float speedCoeff = 10; //rotation speed
void LateUpdate()
{
transform.rotation = Quaternion.Slerp(transform.rotation, targetRot, time.deltatime * speedCoeff);
}