- Home /
Input.acceleration on sphere with rigidbody(gravity)
I am making a school project, where I controll an sphere with devices accelerometer. Now everithing goes well, till I add rigidbody to the sphere. Sphere dose move according to the information from accelerometer for few moments, but then it starts to get stuck. Like it would get stuck in the ground(cube in my case).
I am using this code for accelerometer:
//move object using accelerometer
var speed = 10.0;
function Update () {
var dir : Vector3 = Vector3.zero;
dir.x = -Input.acceleration.y;
dir.z = Input.acceleration.x;
if(dir.sqrMagnitude > 1)
dir.Normalize();
dir *= Time.deltaTime;
transform.Translate(dir * speed);
}
How can I get this to work. Or is there a different way to apply movement to the object with information from accelerometer and have gravity.
I am developing with JavaScript for Android 2.2
Answer by aldonaletto · Nov 03, 2013 at 02:25 AM
Translate by default acts in the local directions, what is a disaster for a sphere with a rigidbody: as the sphere rotates, the X and Y local directions at some moment will roughly point at the ground, making the sphere get stuck. Specify Space.World in Translate, and the world X and Y will be used instead:
transform.Translate(dir * speed, Space.World);
im moving a sphere with forces (you can see what i have done by following the Unity project 00 on how to make a moving sphere) if i place this translate i can
t even see the sphere when entering the game because it probably flies always at any little movement in the device... if i put this rigidbody.AddForce(Input.acceleration speed Time.deltaTime); ins$$anonymous$$d of the translate it actually works kind off... because when the device is in the ground with the home button on the right the sphere goes back, for it to stop move i have to hold the device with the home button on the left and the screen facing back. sry if it`s hard to understand since english isn`t my native language.
You have a totally different problem: the accelerometer axes aren't aligned to your game's axes. From your description, in your game the Z axis goes forth and back, but in the accelerometer the Z axis is perpendicular to the screen, pointing to the user! That's how the accelerometer axes are aligned to a typical device:
You should map them to the axes you want - probably the code below would work in your case:
var force: float = 10.0;
function Update () {
var dir : Vector3 = Vector3.zero;
dir.x = -Input.acceleration.y;
dir.z = Input.acceleration.x;
if (dir.sqr$$anonymous$$agnitude > 1) dir.Normalize();
rigidbody.AddForce(dir * force);
}
Thank you sire it worked perfectly... all i had to do was change the x to = input acceleration.x and the Z to = input acceleration y. you sir deserve a medal