Unity2D analogue stick rotation?
So i am using Unity2D with a load of Vector2s, and want to gradually rotate the character to aim in the direction the analogue stick is pointing.
However, when using my current code, as soon as the turn script is accessed, the character disappears. After some experimentation, I discovered that the character had snapped 90 degrees and was now balanced perpendicular, like paper mario.
I suspect there is a problem somewhere with Vector2 being x y, and so it wont quaternion around z
void FixedUpdate()
{
float TurnV = Input.GetAxis("TurnV");
float TurnH = Input.GetAxis("TurnH");
aimDirection = new Vector2(TurnH, TurnV);
if (TurnV != 0 && TurnH != 0)
{
catBody.transform.rotation = Quaternion.LookRotation(aimDirection);
}
}
Answer by RealoFoxtrot · Apr 29, 2017 at 02:17 PM
Okay, my solution found from around the internet was to use Mathf.Atan2
Ends up looking like this:
void FixedUpdate()
{
aimAngle = Mathf.Atan2(TurnH, TurnV) * Mathf.Rad2Deg;
if (TurnV != 0 && TurnH != 0)
{
catBody.transform.rotation = Quaternion.AngleAxis(aimAngle, Vector3.forward);
}
}
There are a few extra things, like having a check for the character being in the air, and catbody is the name of the rigidbody2d attached.
it's not perfect yet. I actually want to lerp between the current angle, and the analogue stick angle. But for a start, this works
=========== Edit:
Okay, I have already solved the lerp issue. Will try to include all the relevant code now:
protected Rigidbody2D catBody;
protected Vector2 aimDirection; //direction the cat is pointing, jump direction
protected float aimAngle;
protected Quaternion aimRotation;
void Start ()
{
catBody = GetComponent<Rigidbody2D> ();
}
void FixedUpdate()
{
float TurnV = Input.GetAxis("TurnV");
float TurnH = Input.GetAxis("TurnH");
aimDirection = new Vector2(TurnH, TurnV);
aimAngle = Mathf.Atan2(TurnH, TurnV) * Mathf.Rad2Deg;
if (TurnV != 0 && TurnH != 0)
{
aimRotation = Quaternion.AngleAxis(aimAngle, Vector3.forward);
catBody.transform.rotation = Quaternion.Slerp(catBody.transform.rotation, aimRotation, turnSpeed * Time.time);
}
Outside of the code, the TurnV and TurnH input deadzone needs to be set to 0.03
Thanks! This helped me turn a character naturally with analog stick movement. The only thing I did differently in my case was use Vector3.up ins$$anonymous$$d of forward to turn the character as he moves. Thanks for the great solution!
Your answer
Follow this Question
Related Questions
strange rotation in 2d 0 Answers
Enemy's projectile is firing at the opposite direction when it's y-axis align with the player's 0 Answers
how do i make my sprite turn to face the direction that my cursor is moving? 0 Answers
How to fix spite character changing position when turning? 1 Answer
How do you instantiate an object at the tip of a rotating object? 1 Answer