Hello guys Im trying to move my player with a joystick for a mobile game project.I want my player to move at full speed or not at all but with my code down below I cant move my character horizontally but vertically is working fine.
public class TudmanMovement : MonoBehaviour
{
public FloatingJoystick joystick;
public float runSpeed = 40f;
public Rigidbody2D myRigidbody;
public Vector2 move;
private void Start()
{
myRigidbody = GetComponent<Rigidbody2D>();
myRigidbody.velocity = Vector2.zero;
}
private void Update()
{
move.x = joystick.Horizontal;
move.y = joystick.Vertical;
}
public void FixedUpdate()
{
if (joystick.Horizontal >= .3f)
{
myRigidbody.velocity = Vector2.right * runSpeed;
}
else if (joystick.Horizontal <= -.3f)
{
myRigidbody.velocity = Vector2.left * runSpeed;
}
else
{
myRigidbody.velocity = Vector2.zero;
}
if (joystick.Vertical >= .3f)
{
myRigidbody.velocity = Vector2.up * runSpeed;
}
else if (joystick.Vertical <= -.3f)
{
myRigidbody.velocity = Vector2.down * runSpeed;
}
else
{
myRigidbody.velocity = Vector2.zero;
}
}
}
Do you know that just overwriting the velocity doesn’t magically keep what was there before? Setting the velocity to move right then setting it to move up just means it moves up.
That’s no different than you having a field with a value of (10,0) then writing (0,20) to it and expecting it to be (10,20). It’ll be (0,20).
You should read your input and form a Vector2 and assign the velocity once. Modify the X for the horizontal only and Y for the vertical.
Also, constantly reading/writing to a native component means it’s taking trips to/from the engine for that value. Just read it once, modify it as much as you like then write it back once.
When ever you set the velocity to Vector2.up or Vector2.down then you are setting the velocity x to 0. You are also setting the velocity to Vector2.zero whenever the player is not moving up or down.
Everything works fine now the main problem is gone but there is still a problem remains and that is when the game starts for the first time.The first touch is not works no joystick appears no direction can be given it just goes straight at bottom left position till you untouch it any ideas?
Quite simply, it’s yours or 3rd party code for your joystick so you should debug it to determine why it gives you those values, presumably (-1,-1). It’s nothing to do with physics though so impossible to tell you.