- Home /
The question is answered, right answer was accepted
Using Joystick for movement
Hello there, I am making a 2d xbox game and I have a code that makes the character move depending on the the left joystick axis
so here's the code
#pragma strict
private var movement : Vector3 = Vector3.zero;
var jumpheight = 4;
function Update () {
var controller : CharacterController = GetComponent(CharacterController);
var grounded = controller.isGrounded;
var LeftJoyStickPressed = false;
var LeftJoystick = Input.GetAxis("360_LeftJoystick");
if(LeftJoystick == false){
LeftJoystick = 0;
LeftJoyStickPressed = false;
}
if(LeftJoystick == -1)
{
transform.position -= transform.right * Time.deltaTime;
LeftJoyStickPressed = true;
}
if(LeftJoystick == 1)
{
transform.position += transform.right * Time.deltaTime;
LeftJoyStickPressed = true;
}
if(!grounded){
movement.y += Physics.gravity.y * Time.deltaTime;
controller.Move (movement * Time.deltaTime);
}
if(Input.GetButton("360_AButton") && grounded == true){
movement.y = jumpheight;
controller.Move(movement * Time.deltaTime);
}
Debug.Log("" + grounded);
Debug.LogWarning("" + Input.GetButtonDown("360_AButton"));
Debug.LogError("" + Input.GetAxis("360_LeftJoystick"));
Debug.Log("" + LeftJoyStickPressed);
}
So my problem is that when I am not tapping the left joystick the value of left joystick is 1 so the character position is always incrementing by one. I don't know how to fix this. Help would be very much appreciated, Thank you :)
Well, firstly, you don't need the double conditionals for your player movement. Just use:
if($$anonymous$$athf.Abs(Input.GetAxis("360_LeftJoystick")) > 0.08) //$$anonymous$$athf.Abs converts all values to a positive value, so this will tell you if it's below or above 0, by at least 0.08 (to compensate for joystick over-sensitivity)
{
transform.position = moveSpeed * LeftJoystick * Time.deltaTime; //add a moveSpeed Vector2 variable so you can set your move speed...
}
I'm not sure this code is even working:
if(LeftJoystick == false){
LeftJoystick = 0;
LeftJoyStickPressed = false;
}
LeftJoystick is a float, not a bool, it should be if == 0. Though you shouldn't even need this because you can just add:
else{
LeftJoyStickPressed = false;
}
After the $$anonymous$$athf.Abs line I gave ya.
Also, are you not using a Rigidbody?
thanks for your time and help :)
I also turned down the sensitivity of the axis big time and that helped to