1
\$\begingroup\$

So, I am making a 2D airplane game right now and I wanted to know how to move my player automatically but I can still control where it should go or the direction. How do I code this using Mobile joystick?


CODE:

public float moveSpeed;

Rigidbody2D myBody;

protected Joystick joystick;

void Start()
{
    myBody = GetComponent<Rigidbody2D>();
    joystick = FindObjectOfType<Joystick>();
}

// Update is called once per frame

void Update()
{
    myBody.velocity = new Vector2( joystick.Horizontal * moveSpeed, joystick.Vertical * moveSpeed );
}
\$\endgroup\$
1
  • \$\begingroup\$ Input.GetAxis(), check google "Input Manager unity". \$\endgroup\$
    – Nick
    Mar 29 '20 at 12:53
1
\$\begingroup\$

It sounds like you want something like this:

// Minimum amount of joystick deflection that should count to change direction.
public float joystickThreshold = 0.1f;

// Let's save a vector for our current direction of travel.
// (Initialize this to your default movement direction if you don't want to spawn at rest)
Vector2 moveDirection; 

// ...(I'm skipping over your other member variables & Start to be concise)

void Update()
{
    Vector2 stick = new Vector2(joystick.Horizontal, joystick.Vertical);

    // If the player leans the stick far enough, update our direction of movement.
    if(stick.sqrMagnitude > joystickThreshold * joystickThreshold) {
        moveDirection = stick.normalized;
    }

    // Continue moving in the last chosen direction.
    myBody.velocity = moveDirection * moveSpeed;
}
\$\endgroup\$
1
  • \$\begingroup\$ Thank you so much! This code helps my problem! I've been trying to understand the problem you told me but glad you turn it into a code. I will make sure to study this. \$\endgroup\$
    – Saidus
    Apr 2 '20 at 4:05
0
\$\begingroup\$

I don’t know enough about Unity in particular to know how to get the relevant information, but it sounds like the engine-independent way to describe what you want is the following:

If there was any input, store the indicated direction. On each frame, move in the last stored direction.

I’m assuming here that if the player returns the joystick to the center you want the plane to keep moving in the last direction it was moving in. So you might need to specify a deadzone in the center where you don’t count the joystick movement as input for the “if there was any input” check above.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.