I am developing an game similar to Doodle Jump, where the character continually jumps upwards from platform to platform. The user controls the character by tilting his device left and right. There is a very specific effect that I am trying to achieve, and I’m going to have to ask for help to pull it off.
The character’s position on the screen should be determined by how the player is tilting the device. When the device is held upright, the character should be at the center of the screen. When the device is tilted left or right, the character should smoothly move left or right, but he should always return to the center of the screen when the device is held upright again.
I’ve tried to achieve this effect using rigidbody.AddForce and rigidbody.velocity, but neither of those two methods produces the desired effect.
How would I make an object move left and right when tilting a device, and return to the center of the screen when the device is not being tilted? My attempts to pull this off have been catastrophically bad, so my approach is probably wrong. Before I waste any more time barking up the wrong tree, I’ve come here to ask: How would I accomplish the kind of behavior that I’m describing?
1- Using Input.acceleration:
The accelerometer reports the current acceleration in G’s as a Vector3 in its own coordinate system (the Z axis is reversed relative to Unity’s):
If you want to run your game in landascape orientation (home button at the right hand), the docs’ Input.acceleration example is a good starting point. This example assumes that the screen shows the XZ plane (a typical top-down configuration). If in your game the screen shows the XY plane instead (a typical side-scroller), the code should be modified a little, like below - it’s also a good idea to filter the acceleration data (it’s too jerky without filtering):
// Move object in XY using accelerometer (home button at right hand)
var speed: float = 6.0;
var filter: float = 5.0;
private var accel: Vector3;
accel = Input.acceleration;
// filter the jerky acceleration in the variable accel:
accel = Vector3.Lerp(accel, Input.acceleration, filter * Time.deltaTime);
// map accel -Y and X to game X and Y directions:
var dir = Vector3(-accel.y, accel.x, 0);
// limit dir vector to magnitude 1:
if (dir.sqrMagnitude > 1) dir.Normalize();
// move the object at the velocity defined in speed:
transform.Translate(dir * speed * Time.deltaTime);
2- Character position in the screen:
The behaviour you describe looks more like a camera follow script (like SmoothFollow), which will follow the player when it’s trying to go out of screen.