tilt controls

Hi guys,

I have the following code attached to a rigidbody2d -


using UnityEngine;
using System.Collections;

public class playerMove : MonoBehaviour {

//declare the max speed
public float maxSpeed= 2f;
// the player character is facing to the right by default
bool facingRight= true;

Animator anim;

void Start ()
{
anim= GetComponent();
}

void FixedUpdate ()
{

float move= Input.GetAxis (“Horizontal”);

anim.SetFloat (“Speed”, Mathf.Abs(move));

rigidbody2D.velocity= new Vector2 (move * maxSpeed, rigidbody2D.velocity.y);

if(move > 0 !facingRight)
Flip();
else if(move < 0 facingRight)
Flip();
}

void Flip()
{
facingRight= !facingRight;
Vector3 theScale= transform.localScale;
theScale.x *= -1;
transform.localScale= theScale;
}
}

this allows my character to flip when it travels in the opposite direction and correctly cycle through the animations.
It works perfectly on my laptop but I’m making this game for android and when I run this on my Kindle, obviously the left and right arrow keys wont work on there.

I basically want to know how I can implement tilt controls to this code so I works on my kindle.

I’m new to c#, I got this code from a live training session by the unity developers.

I have this snippet of code which allows tilt controls to work but when I use this the animation the flip and walk cycle don’t work.
transform.Translate(Input.acceleration.x * Time.deltaTime,0,
-Input.acceleration.z * Time.deltaTime);

Cheers guys

You shouldn’t move a rigidbody(2D) using transform.Translate().
I suggest you save whatever axis you need of the accelerometer to float move in Update() and apply it in fixed update using
rigidbody2D.AddForce() or by directly manipulating the velocity of the rigidbody2D.

I’d guess that Flip() and the animation don’t work because they are relying on the move variable which you are not assigning anything to except key input from A D or LeftArrow RightArrow. This is easily fixed if you save the accelerometer data into the move var as stated above.

refer to this picture for the currect axis

1640288--101715--$device_axes.png

I changed float move= Input.GetAxis (“Horizontal”); to float move= Input.acceleration.x; and it worked just how I wanted.
Is my method of doing this inefficient as it is now?
My main goal was to just get it working but obviously if its and easy fix (remember i’m new to c#) than I might as well make it the best I can.

Also, where are the commands to use the left and right arrow (or A and D) in this code? I got this script from the unity live training and was surprised when the keys made the player move as I couldn’t see anywhere where the keys had been assigned.

Cheers :slight_smile:

The Input.GetAxis(“Horizontal”) is set to A and D and the left and right keys by default.