- Home /
Transforming slowly
Hi there,
I'd like to be able to adapt something slowly. For example, the following code:
if (Input.GetKeyDown("z"))
transform.eulerAngles = new Vector3(0, 0, 0);
I've attached that to my little car as a way of flipping it if lands on its roof. But it will just instantly change to that rather than slowly roll over. I've been looking into Slerp but I can't seem to get my head around it.
Any info is a great help dudes. Cheers
Answer by Landern · Nov 19, 2014 at 05:04 AM
Here's an example using smooth damp. In the inspector smoothTime was set to 2.0.
using UnityEngine;
using System.Collections;
public class Smooth : MonoBehaviour
{
public float smoothTime; // assign in inspector
private bool flipping = false;
private Transform thisTransform;
private Vector3 vel = Vector3.zero;
public void Start()
{
// cache this objects transform. Otherwise small hits, under the covers GetComponent is used in < unity 5
thisTransform = transform;
}
public void Update()
{
if (Input.GetKeyDown("z"))
flipping = true;
if(flipping && thisTransform.eulerAngles != Vector3.zero)
{
float speed = Time.deltaTime * smoothTime;
thisTransform.eulerAngles = Vector3.SmoothDamp(thisTransform.eulerAngles, Vector3.zero, ref vel, speed);
}
else if (flipping && transform.eulerAngles == Vector3.zero)
{
flipping = false;
}
}
}
Thanks Landern! I've attached this as a script of its own but once you hit Z the player then flips wildly (if the speed is high) or snaps into place (if the speed is low). And then once in position turning on the y axis is locked up.
I've practically just started with C# so I'm not sure of some parts of this, especially the thisTransform = transform; in void start. I'm assu$$anonymous$$g thats where my problem lies, as the rest of the code looks solid.
Funnily enough though, I was originally after an automatic balance script, basically spin correction on the Z axis, but I just couldn't get my head around the logic of it. This seems close to what I was ai$$anonymous$$g for, but what do you think.
Sorry if this is going off topic, I tend to start elaborating straight away :/
Your answer
Follow this Question
Related Questions
How to get Angle float of specific axis.(Turret clamping related). 2 Answers
Door opening - Vector.slerp is really glitchy 1 Answer
Object wont rotate in the opposite direction 1 Answer
Vector3.Slerp not working 2 Answers
Euler Angles and Vectors 3 Answers