- Home /
Flip the gameobject when tilting 2D C#
Hi Developers,
I have a simple tilt code and a simple flip code and I want to work these codes together. My game is simple 2D top down game and I want my character do flip when the phone is tilting. Character have to look right when tilting right and have to look left when tilting left.
public class Tilt : MonoBehaviour {
public float speed = 50.0F;
bool facingRight = true;
void Update() {
Vector3 dir = Vector3.zero;
dir.x = Input.acceleration.x;
if (dir.sqrMagnitude > 1)
dir.Normalize();
if (dir.sqrMagnitude > 1 && !facingRight)
Flip ();
else if (dir.sqrMagnitude < 1 && facingRight)
Flip ();
dir *= Time.deltaTime;
transform.Translate(dir * speed);
}
void Flip()
{
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
if (dir.x >= 0 && !facingRight)
Flip ();
else if (dir.x < 0 && facingRight)
Flip ();
this should work.
Thank you for your answer but it does'nt work. I can't see my character when I try this code. Sometimes character appears for a short duration and I can see it is flipped but character moves too fast and it is invisible.
Are you sure the character is invisible and not just off the screen? Or is it perhaps tilted such that the sprite is flipping on the wrong axis (so it's not laying flat)? I have had both of these problems in the past with my 2d games.
Answer by JotterMelon · Jan 05, 2015 at 03:04 PM
I can't understand why the character is invisible. Can anybody explain
Your answer
Follow this Question
Related Questions
(2D sidescrolling platformer) Flipping my character right or left depending on the mouse? 2 Answers
My vehicle wont perform both the Tilt and Turn 0 Answers
How to tilt texture every second with this Unity script ? 0 Answers
Using Mathf.Clamp in unity for boundries 2 Answers
Is there a way to know if the device supports tilt? 1 Answer