# Help with joystick movement in 2d game

Greetings to everyone from already doi thanks for your attention.

I have a problem with the script I use to move my character with the single joystick assets of unity.

So far the precionar the right, left and side up but the character moves when the joystick down precionar character goes well.

I leave the code that I have so far

``````public var velocidad   : Vector2  = new Vector2(50, 50);
private var movimiento : Vector2;
private var thisTransform : Transform;
private var velocity : Vector2;
var moveJoystick : Joystick;

function Start (){
thisTransform = GetComponent( Transform );
}
function Update () {

var movement : Vector2 = thisTransform.TransformDirection( Vector2( moveJoystick.position.x, moveJoystick.position.y ) );
var absJoyPos : Vector2 = Vector2( Mathf.Abs( moveJoystick.position.x ), Mathf.Abs( moveJoystick.position.y ) );

if ( moveJoystick.position.y > 0 ){

movimiento = new Vector2(velocidad.x * absJoyPos.x, velocidad.y * absJoyPos.y);
}else{
movimiento = new Vector2(velocidad.x * absJoyPos.x, velocidad.y * absJoyPos.y);
}

if ( moveJoystick.position.x > 0){
movimiento = new Vector2(velocidad.x * absJoyPos.x, velocidad.y * absJoyPos.y);
}else{
movimiento = new Vector2(velocidad.x * absJoyPos.x * -1, velocidad.y * absJoyPos.y);
}
}
function FixedUpdate(){

rigidbody2D.velocity = movimiento;

}
``````

The game is 2D and I just need to move in the x and y axes, which as I said you get what but when you press the joystick down the character goes.

I have days trying to fix this and I have searched many places without finding the solution.

Thank you very much and sorry for my bad English

I’m afraid I don’t fully understand your question, but if all you are trying to do is set the rigid body’s velocity based on the joy stick, why not:

``````function Update () {

//get the velocity (you might even just be able to do newVelocity = moveJoystick.position
//but I don't know about moveJoystick so am not sure)
var newVelocity : Vector2 = Vector2(moveJoystick.position.x, moveJoystick.position.y);

//maybe we multiply it by something if we want the player to be faster or slower
newVelocity *= 5.0f;

//now store it in the rigid body
rigidbody2D.velocity = newVelocity;
}
``````

Just so you’re aware, the most obvious bug in your code is on line 19 - for your code to work at all you would need to add a ‘-1’ to the y, just like you add a -1 to the x in the other section. However I think you’ve made it a little more complex than it needs to be, and there’s several other reasons you will have problems with it, so I’d go with my example above!

-Chris

Or just remove the absJoyPos and use the raw input to move.

Also don’t mix languages (spanish english) it make your code harder to read.