- Home /
Joystick Diagonal?
Hello friends, I have currently got some code that let's me trigger animations with joystick input. I can do Up,Down,Left,Right but I don't know how to do diagonal
can someone help me please?
if (joystick1.Horizontal >= 0.9f)
{
anim.Play("NewShove");
}
Answer by detzt · May 05, 2020 at 08:27 PM
I can recommend the new InputSystem in general (see InputSystem package).
With the attached code, I created an InputProcessor that rotates the raw Input by a configurable amount of degrees (45 for diagonal). Just put the script somewhere in your project and add "Rotate" as a Processor.
using UnityEditor;
using UnityEngine;
using UnityEngine.InputSystem;
/// <summary>
/// Input processor to rotate a two dimensional input by the configured degrees
/// </summary>
#if UNITY_EDITOR
[InitializeOnLoad]
#endif
public class RotateProcessor : InputProcessor<Vector2> {
[SerializeField, Tooltip("The angle in degrees to rotate the vector by")]
private float rotateDegrees = 45f;
#if UNITY_EDITOR
static RotateProcessor() {
Initialize();
}
#endif
[RuntimeInitializeOnLoadMethod]
private static void Initialize() {
InputSystem.RegisterProcessor<RotateProcessor>();
}
/// <summary>Rotates the given vector <paramref name="value"/> by the configured <see cref="rotateDegrees"/></summary>
public override Vector2 Process(Vector2 value, InputControl control) {
float sin = Mathf.Sin(degrees * Mathf.Deg2Rad);
float cos = Mathf.Cos(degrees * Mathf.Deg2Rad);
float vx = value.x;
float vy = value.y;
value.x = cos * vx - sin * vy;
value.y = sin * vx + cos * vy;
return value;
}
}
If you just want to rotate this one joystick, here's a snippet:
float degrees = 45;
float vx = joystick1.Horizontal;
float vy = joystick1.Vertical;
float sin = Mathf.Sin(degrees * Mathf.Deg2Rad);
float cos = Mathf.Cos(degrees * Mathf.Deg2Rad);
Vector2 rotated = new Vector2(cos * tx - sin * ty, sin * tx + cos * ty);
if(rotated.x >= 0.9f) anim.Play("NewShove");
Answer by billytipewhite · May 06, 2020 at 10:08 AM
Thank you so much for that in depth response @detzt!
However, I'm am not sure on how to implement your code as I am new in the C# game. Do you know a fix that could be more suited to my current approach (Simple) haha.
Thank's again :)
See the code snipped in the lower part of my answer ;) The rotated Vector2 contains the joystick diagonal axes. rotated.x and rotated.y are the diagonal values similar to joystick1.Horizontal and .Vertical
Did this solve your problem @billytipewhite ? If so, you can accept the answer by clicking the blue tick below it ;)
Your answer
Follow this Question
Related Questions
Problem with diagonal movement + animations 1 Answer
Pay animation if joystick pushed to left and another if joystick is pushed to right 2 Answers
Animated character orientation? 1 Answer
360 Trigger Pressing both Triggers at the same time 1 Answer
What do I need to add to make an iOS joystick movement have my character animate? 0 Answers