Help for a Dash Script
HEY!
Please help! I want to make a 2D dash script for my 2D game. The problem appears that this is too large, ayone can make it shorter??
void Angle()
{
if(Input.GetKey(KeyCode.A) && !Input.GetKey(KeyCode.W) && !Input.GetKey(KeyCode.S))
{
X = -1f;
Y = 0f;
}
if (Input.GetKey(KeyCode.A) && Input.GetKey(KeyCode.W))
{
X = -0.70f;
Y = 0.70f;
}
if (Input.GetKey(KeyCode.A) && Input.GetKey(KeyCode.S))
{
X = -0.70f;
Y = -0.70f;
}
if (Input.GetKey(KeyCode.S) && !Input.GetKey(KeyCode.W) && !Input.GetKey(KeyCode.D))
{
X = 0f;
Y = -1f;
}
if (Input.GetKey(KeyCode.S) && Input.GetKey(KeyCode.D))
{
X = 0.70f;
Y = -0.70f;
}
if (Input.GetKey(KeyCode.D) && !Input.GetKey(KeyCode.S) && !Input.GetKey(KeyCode.W))
{
X = 1f;
Y = 0f;
}
if (Input.GetKey(KeyCode.D) && Input.GetKey(KeyCode.W))
{
X = 0.70f;
Y = 0.70f;
}
if (Input.GetKey(KeyCode.W) && !Input.GetKey(KeyCode.A) && !Input.GetKey(KeyCode.D))
{
X = 0f;
Y = 1f;
}
}
The X and Y are the cosinus and sinus write it straight forward. They are the angles that creates when pressed the keys.
With that event, i transform a velocity to make it go to the direction I want.
If you need more information ask please.
Answer by NinjaISV · Nov 22, 2017 at 01:10 AM
Your code is quite messy and hard to follow. I would advise taking an approach like this:
private Vector2 GetInputVector () {
Vector2 vector = Vector2.zero;
bool up = Input.GetKey(KeyCode.W);
bool down = Input.GetKey(KeyCode.S);
bool left = Input.GetKey(KeyCode.A);
bool right = Input.GetKey(KeyCode.D);
if (up == true) {
vector.y = 1;
} else if (down == true) {
vector.y = -1;
}
if (left == true) {
vector.x = -1;
} else if (right == true) {
vector.x = 1;
}
return vector.normalized;
}
This will return a direction vector that will have a magnitude of 1, yet it will move you in any direction. If you wish to change the keys (W, A, S, D) you can by editing the local bool variables in the top of the function.
Glad I could help! Please consider up-voting my answer, thanks! :)