HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Moving character in Unity3D based on accelerometer input

Submitted by: @import:stackexchange-codereview··
0
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.

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 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.