patterncsharpModerate
Moving character in Unity3D based on accelerometer input
Viewed 0 times
unity3dcharacterinputaccelerometermovingbased
Problem
I am building a infinite vertical platformer for mobile platforms using Unity3D. I am using the accelerometer to move the character left and right on the screen.
Basically the farther the device is tilted the faster the character moves. I'm pretty sure there is a way better way to write this code but I'm pretty terrible at math and I can't figure it out. Any suggestions on cleaning this up a bit?
if (Input.acceleration.y > -0.2f && Input.acceleration.y -0.5f && Input.acceleration.y 0.2f && Input.acceleration.y -0.7f && Input.acceleration.y 0.5f && Input.acceleration.y 0.9f) {
maxSpeed = 40;
}Basically the farther the device is tilted the faster the character moves. I'm pretty sure there is a way better way to write this code but I'm pretty terrible at math and I can't figure it out. Any suggestions on cleaning this up a bit?
Solution
I know absolutely nothing about c# or unity3d, so if there's a language specific assist, I have no idea about it!
I notice each condition checks
First of all, the negatives are confusing. Find the absolute value first.
I'm going to assume a number followed by an "f" means float. So maybe we need something like:
Great, now it's going to be easier to handle this!
Now all we need is a simple check like so:
Your original numbers were a little weird, but if you meant for such a strange pattern, correct me!
I notice each condition checks
Input.acceleration.y, so that's one bit of information that repeats. I also notice we have three speeds, yet we have seven conditionals!First of all, the negatives are confusing. Find the absolute value first.
I'm going to assume a number followed by an "f" means float. So maybe we need something like:
float acceleration = Math.Abs(Input.acceleration.y);Great, now it's going to be easier to handle this!
Now all we need is a simple check like so:
if (acceleration < 0.2f) {
maxSpeed = 17;
} else if (acceleration < 0.9f) {
maxSpeed = 25;
} else {
maxSpeed = 40;
}Your original numbers were a little weird, but if you meant for such a strange pattern, correct me!
Code Snippets
float acceleration = Math.Abs(Input.acceleration.y);if (acceleration < 0.2f) {
maxSpeed = 17;
} else if (acceleration < 0.9f) {
maxSpeed = 25;
} else {
maxSpeed = 40;
}Context
StackExchange Code Review Q#58596, answer score: 10
Revisions (0)
No revisions yet.