-1

I want to move an object with acceleration input in unity:

if (...)
transform.translate(vector2.right*speed);
else if (...)
transform.translate(vector2.left*speed);

I don't know what the conditions should be

Ali Safari
  • 87
  • 1
  • 1
  • 6
  • 2
    What will make the object move right? What will make your object move left? The answers to these questions will be your conditions. – ryeMoss Dec 20 '17 at 20:42

1 Answers1

2

Well, you can technically achieve this movement without using conditions at all. Simply put something like this in either Update() or FixedUpdate() (FixedUpdate() is recommended).

Vector2 dir = Vector2.zero;
void FixedUpdate()
{
   dir.x = Input.acceleration.x;
   transform.translate(dir * speed * Time.deltaTime);
}

This is because when your phone is placed flat on a surface Input.acceleration.x is 0. If it is tilted to the right, the value will be positive. If tilted to the left, the value will be negative. Thus leaving you free of conditionals.

Brandon Miller
  • 1,534
  • 1
  • 11
  • 16
  • 1
    I just want to add that even if Input.GetAxis("Horizontal") would be used, there would be no need for conditions. – Tobias Theel Dec 20 '17 at 21:03
  • Very true! I try to avoid conditions in movement logic as much as possible, because it tends to make things choppy. – Brandon Miller Dec 20 '17 at 21:05
  • Thanks Brandon. look, I have 2 classes for my character. In first class, I make the character jump by add forced on collision enter(character has also gravity) and in second I want make it move left and right by acceleration. I did what you said but the character stops jumping after 1 or 2 jumps, any Idea? – Ali Safari Dec 25 '17 at 04:58