- Home /
The question is answered, right answer was accepted
Rigidbody with Accelerometer
Hello community! I wanted to control a rigidbody by using accelerometer on android, i printed something like this:
function Update() {
if((Input.acceleration.x) > 0)
{
rigidbody.AddForce(Input.acceleration.x, 0, 0);
}
else if((Input.acceleration.x) < 0)
{
rigidbody.AddForce(Input.acceleration.x, 0, 0);
}
else
{
rigidbody.AddForce(Input.acceleration.x, 0, 0);
}
}
But nothing worked. So, i hope that Input.accelereation.x is integer, since i can't find any information about this function ^^.
Hope for a fast answer =) Thx
Look, imagine that rigidbody located at a big hill, then it will roll down, and while it is, you can move rigidbody with accelerometer, to the left and right.
Out of curiosity, try your code with Force$$anonymous$$ode.Impulse and see what happens.
You have the same exact statement in every condition. This means no matter what, you're adding force depending on the same axis used. First things first, clean this up.
function Update()
{
rigidbody.AddForce(Input.acceleration.x, 0, 0);
}
Then have a look HERE.
As i commented in answer Above, This code works strange: Rigidbody moves in 2 different directions.
Of course it does. When you choose to move something on the axis depending on which why you're tilting, that's what happens. It's like hitting left or right keys... What exactly are you trying to do besides this? Please make your question more clear.
Are you, erm. Are you trying to get this working in the editor? :P
If not I bet you are using a HTC
What do you mean oO? In editor i can't find accelerometer. No, Xperia arc S
Answer by RescuerRus · Sep 23, 2013 at 01:33 AM
I finally fixed it. Just had to use RigidbodyConstraints to freeze the rotation of the rigidbody. It was rotating on different axes, which was causing it to move in the wrong direction.
for posting your solution. If any other answers or comments seemed to be helpful, please be so kind to vote them up as well. Happy Developing :)
Answer by meat5000 · Sep 23, 2013 at 12:10 AM
Just try this in a script and see what it gives you.
var dir : Vector3 = Vector3.zero;
function Update ()
{
dir.x = -Input.acceleration.x;
dir.y = Input.acceleration.y;
dir.z = Input.acceleration.z;
}
function OnGUI()
{
GUI.Box (Rect (20,20,200,200),dir);
}
You will find that x,y,z vary between -1 -> 0 -> 1 depending on the way the device is held. And, it's a Float
I only needed to move rigidbody on x-axis, and btw, still nothing happend. This one worked fine http://docs.unity3d.com/Documentation/ScriptReference/Input-acceleration.html But it worked strange with rigidbody, they somehow conflicted by moving a body in different directions.
Did you look at the OnGUI output to see if your accelerometer is working? Also notice how x is -ve