- Home /
Rotation to joytick direction is so sudden
I have a character rotation to where joystick faces: Code
void Update () {
if (Input.GetKey (KeyCode.Mouse0)) {
x = Mathf.MoveTowards(x,Input.GetAxisRaw ("Horizontal"),(0.1f*tank.manoeuvre)*Time.deltaTime);
y = Mathf.MoveTowards(y,Input.GetAxisRaw ("Vertical"), (0.1f * tank.manoeuvre) * Time.deltaTime);
}
transform.eulerAngles = new Vector3(transform.eulerAngles.x, 0, Mathf.Atan2(x, -y) * Mathf.Rad2Deg);
if(Input.GetButton("Move"))
GetComponent<.velocity=-transform.up*tank.speed;
else
{
GetComponent<Rigidbody2D>().velocity = Vector2.Lerp(GetComponent<Rigidbody2D>().velocity, Vector2.zero, 4f * Time.deltaTime);
}
}
It works when I move the joystick slowly. But when I move the joystick to its reverse (from horizontal1.0, to horizontal-1.0 ) the rotation happens so immediate. I want to make it rotate where the joystick faces, but with a fixed speed. how can I make it? Thanks
Lerp increase goes from faster to slower, I want a fixed speed, which I believed $$anonymous$$oveTowards would do this.
Answer by FlaSh-G · Jul 06, 2017 at 11:30 PM
Instead of interpolating single floats and then putting them into a rotation vector, get a target rotation and interpolate towards that. It's way less complicated (thus less likely to produce errors) and your speed will be handled more correctly.
var input = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));
if(input != Vector3.zero) // Check this because Quaternion.LookDirection doesn't like zero vectors
{
var targetRotation = Quaternion.LookDirection(input);
transform.localRotation = Quaternion.RotateTowards(transform.LocalRotation, targetRotation, speed * Time.deltaTime);
}
Yeah this is probably what you meant when you said "$$anonymous$$oveTowards." What he has done here with RotateTowards is better than Lerp because it's mostly handled for you.
But you did have the wrong idea of Lerp. If it picks up speed then you aren't updating "t" correctly. I'd bet you anything RotateTowards has Lerp under the hood, or the same algorithm anyway.
Yeah, they're related. RotateTowards internally uses SlerpUnclamped, which is a more complicated quaternion lerp.
Your answer
Follow this Question
Related Questions
Flip over an object (smooth transition) 3 Answers
C# Clamp joystick rotation 0 Answers
Making my Game Object face according to direction of mobile joystick 2 Answers
Multiple Cars not working 1 Answer
Cross Platform Joystick Rotation 0 Answers