- Home /
my rotate object back and forth script is causing my object to start at 0 degrees, not from, the angle i have positioned it at.
so I'm trying to make a car travel down a road and rotate back and forth on the Y axis so that it swerves across the road as it moves. the car is placed with its Y rotation at -180 but as soon as the level starts, the script runs it from Y 0, making the car go in the wrong direction and I can't figure out what I need to do. I tried using localRotation but that changed nothing. Here's what I've got.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CpuController : MonoBehaviour
{
[SerializeField]
private float vehicleSpeed = 10f;
public float speed = 1;
public float RotAngleY = 45;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.Translate(Vector3.forward * Time.deltaTime * speed);
float rY = Mathf.SmoothStep(0, RotAngleY, Mathf.PingPong(Time.time * speed, 1));
transform.rotation = Quaternion.Euler(0, rY, 0);
Answer by andzq · Jun 29, 2021 at 10:54 PM
SmoothStep(min, max, t) interpolates between a min and max value for a given t (0-1).
-------------------
Your min value is 0 and your max is RotAngleY.
-------------------
When the game starts, Time.time is 0 and so will be [Time.time * speed].
-------------------
rY will therefore be what SmoothStep returns at the given t = 0.
-------------------
The filled in values would look like this -> SmoothStep(0, RotAngleY, 0).
-------------------
This will return 0 which leads to your Quaternion.Euler to be given the values (0, 0, 0).
-------------------
Since you directly set Quaternion.Euler(0, 0, 0) as the rotation of the transform, it will override whatever rotation your car had at the start.
What you could do to avoid this is to save the initial localRotation of the car as a Quaternion and ADD the rotation you'll get from your SmoothStep part on top of it like so:
Quaternion initialRotation = transform.localRotation;
void Update()
{
// previous stuff
transform.rotation = initialRotation * Quaternion.Euler( 0, rY, 0);
}
Answer by Ultra_Sun_Bro · Jul 01, 2021 at 09:13 AM
Thanks for answering. I didn't realize that rY was returning 0 and to be honest I don't really understand or how to change it haha.
Unfortunately after adding what you suggested it just made my object spin really fast, but I appreciate the help.