0
votes

I am creating a game in Unity 3d that is using a single joystick. I am trying to figure out how I can rotate a 3d object using the joystick correctly. Basically when the joystick is pushed up (or forward) the object will rotate forward and vice versa for when it is pushed down. My problem is getting the object to rotate correctly if I were to push the up diagonally to the left or right.

My joystick uses gives values (0, 1) for up, (0, -1) for down, (1, 0) for right, and (-1, 0) for left.

How do I get the object to rotate forward or backward and toward the diagonal direction on a joystick? (I'm sorry if this is confusing. I am trying to ask this as simple as I can).

Right now this is what I am using to rotate:

if ((x > 0 && x < .2f) || (x < 0 && x > .2f)) x = 0;
if ((y > 0 && y < .2f) || (y < 0 && y > .2f)) y = 0;

if (x < 0) car.transform.Rotate(car.transform.forward.x * 10f, car.transform.forward.y * 10f, -car.transform.forward.y * 10f);
else if (x > 0) car.transform.Rotate(car.transform.forward.x * 10f, car.transform.forward.y * 10f, car.transform.forward.y * 10f);
else car.transform.Rotate(car.transform.forward.x * 10f, car.transform.forward.y * 10f, 0f);
1
"My problem is getting the object to rotate correctly if I were to push the up diagonally to the left or right." That suggests you have some code that doesn't work. Can you show it? - 31eee384
@31eee384 Now that I tested it, it doesn't work right. It depends on where I am in world space. Some places it rotates right and others it does not so I might as well say I don't have the rotation working at all. Sorry about that. - sabo
@31eee384 Check the edit. Thanks - sabo

1 Answers

2
votes

It looks like you don't understand Transform.Rotate (second overload).

This is the signature of the method:

public void Rotate(float xAngle, float yAngle, float zAngle, Space relativeTo = Space.Self);

xAngle is the number of degrees to rotate around the x axis. Passing a component of the forward vector (car.transform.forward.x) is trying to put a unit vector component into a parameter accepting an angle. The concepts and units simply don't match, so the result will be impossible to describe.

Instead, you should rotate using angles based on the joystick position. Relative mode (the default Space.Self) will mean that the joystick acts relative to the object's current rotation.

Something like this should do it, where x and y are your joystick positions:

car.transform.Rotate(y, x, 0)

You can either carefully look at which joystick axes match with which Unity axes, or try moving the x and y around until it works right. You might also need to negate x or y depending on your preference.