- Home /
Tilt an object when rotating and set it back to normal afterwards
Hi everyone,
Here is my problem. I have an object (basically, a moto) and so far I just make it go on a plane. I can make it rotate so it goes left or right whenever I want. Now, as motos do when they turn, I want my moto to tilt when turning. Here is my Movements
and ControllerManager
class so you can see what i'm working with.
public class ControllerManager : MonoBehaviour
{
public KeyCode forwardKey, leftKey, rightKey;
public float tilt;
private float _fwd, _lateralDirection, _right, _left;
public float Fwd{
get { return _fwd;}
}
public float LateralDirection{
get { return _lateralDirection; }
}
public void Start(){
_fwd = 0;
_right = 0;
_left = 0;
}
public void FixedUpdate(){
// _fwd and _lateralDirection kind of simulates default horizontal and vertical axis values
_fwd += Input.GetKey(forwardKey) ? (_fwd < 1 ? 0.1f : 0) : (_fwd > 0 ? (_fwd < 0.01f ? -_fwd : -0.1f) : 0);
// moto can't turn if not moving forward
_right += Input.GetKey(rightKey) & _fwd != 0 ? (_right < 1 ? 0.1f : 0) : (_right > 0 ? (_right < 0.1f ? -_right : -0.1f) : -_right);
_left += Input.GetKey(leftKey) & _fwd != 0 ? (_left > -1 ? -0.1f : 0) : (_left < 0 ? (_left > 0.1f ? -_left : 0.1f) : -_left);
_lateralDirection = _left + _right;
}
}
public class Movements : MonoBehaviour
{
public float speed;
public float sensibility;
private ControllerManager _controller;
// Start is called before the first frame update
void Start()
{
_controller = GetComponent<ControllerManager>();
}
// Update is called once per frame
void LateUpdate()
{
transform.Translate(Vector3.right * _controller.Fwd * speed * Time.deltaTime, Space.Self);
transform.Rotate(Vector3.up * _controller.LateralDirection * sensibility * Time.deltaTime, Space.World);
}
}
Any ideas ? I have tried to use Animations but I can't seem to make it work : I created two animations TiltRight and TiltLeft. Each of them simply rotates the moto (~ 25 degrees) around fwd axis, respectively right and left. But I'd need to sort of pause the state of the object while turning key are pressed. And I did not achieve that.
Regards.
Is this example in the Unity documentation similar to what you want? $$anonymous$$aybe it can help you: https://docs.unity3d.com/ScriptReference/Transform-rotation.html
It seems to be, but I cannot get it work. Because I cannot rotate the moto anymore. It justs goes back to its inital direction when i stop turning. So basically it goes only along the X axis.