- Home /
Problem with joystick movement
I'm using the standard asset mobile joystick.js script for my controls, but I'm having trouble with my character movement. I'm just trying to move, left, right, up and down using AddRelativeTorque and it works to an extent but not quite the way I want.
I have a ball in the scene and rolls around ok at first, but it seems as though the rotation is throwing the controls off as when the ball is stationary it works fine but when I start moving it, the controls don't behave accordingly.
I'm probably doing this wrong but can anyone help me out here, I would just like to be able to roll my ball in the x and z axis. Here is my code:
#pragma strict
// This script must be attached to a GameObject that has a CharacterController
@script RequireComponent( CharacterController )
var moveJoystick : joystick;
var speed : float = 10; // Ground speed
private var thisTransform : Transform;
private var character : CharacterController;
function Start()
{
// Cache component lookup at startup instead of doing this every frame
thisTransform = GetComponent( Transform );
character = GetComponent( CharacterController );
}
function Update()
{
//transform.eulerAngles.y = 0;
if(moveJoystick.position.x >= 0.5)
{
rigidbody.AddTorque(Vector3.up * 10);
}
else if(moveJoystick.position.x <= -0.5)
{
rigidbody.AddTorque(Vector3.down * 10);
}
else if(moveJoystick.position.y >= 0.5)
{
rigidbody.AddTorque(Vector3.left * 10);
}
else if(moveJoystick.position.y <= -0.5)
{
rigidbody.AddTorque(Vector3.right * 10);
}
}
You're going to want to add torque relative to the rotation of your camera or an empty game object ins$$anonymous$$d of the ball itself. The ball is spinning and so it's rotation is changing which is screwing up the torque. If you make an empty game object and make it the parent of the ball you can simply use the transform.forward of the parent to rotate the ball.
So with the ball as a child of an empty do this:
Var ball : GameObject; //set the ball to this in the inspector.
Function Update()
{
if(moveJoystick.position >= 0.5)
{
ball.rigidbody.AddTorque(Vector3.Forward) *10;
}
}
Now remove the script from the ball itself and attach it to the empty game object.
Answer by RandomUser123 · Aug 04, 2014 at 11:58 PM
Cheers for the input drex150 but i managed to fix it, i had my Vectors all wrong, i should have just done them one by one instead of assuming what the values should have been. I was using Vector3.up
and Vector3.down
instead of Vector3.back
and Vector3.forward
Here's my working script, everything up to the if statements is the same:
if(moveJoystick.position.x >= 0.5)
{
rigidbody.AddTorque(Vector3.back * 10) ;
}
else if(moveJoystick.position.x <= -0.5)
{
rigidbody.AddTorque(Vector3.forward * 10);
}
else if(moveJoystick.position.y >= 0.5)
{
rigidbody.AddTorque(Vector3.right * 10);
}
else if(moveJoystick.position.y <= -0.5)
{
rigidbody.AddTorque(Vector3.left * 10);
}