# How to move my character by itself but I can still move its direction or where it is going, using Mobile Joystick?

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 );
}

• Input.GetAxis(), check google "Input Manager unity".
– Nick
Mar 29 '20 at 12:53

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;
}

• 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. Apr 2 '20 at 4:05

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.