- Home /
Flip 2D Character with Keys without moving
Hey, guys! I got into Unity really recently and I have been working on a simple game. So simple, I don't even want to move my character throughout the level. I just need to make him flip everytime I press the Left and Right arrow keys. I've been learning some stuff here and there and searching everywhere but it's not enough for me to understand this yet, so I needed your help! I'm sorry if I look like I'm making you do all the work, it's not my wish to do so! I have this piece of code but I need to know where to change exactly so I can use the arrow keys and make him JUST flip and not move.
using UnityEngine;
using System.Collections;
public class FlipCharacter : MonoBehaviour {
public float maxSpeed = 1f;
bool facingRight = true;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void FixedUpdate ()
{
float move = Input.GetAxis ("Horizontal");
GetComponent<Rigidbody2D>().velocity = new Vector2 (move * maxSpeed, GetComponent<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;
}
}
If you need anything more, tell me! Thanks in advance!
Answer by Serdan · Sep 07, 2015 at 11:47 PM
From what I can tell it should already work, though I would have done it differently. What happens when you use it?
It's generally best to use Input.GetAxis(), but if you just want it to work you can use the following and expand on that:
using UnityEngine;
using System.Collections;
public class FlipCharacter : MonoBehaviour
{
void FixedUpdate()
{
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
SetDirection(-1);
}
if(Input.GetKeyDown(KeyCode.RightArrow))
{
SetDirection(1);
}
}
void SetDirection(float direction)
{
Vector3 theScale = transform.localScale;
theScale.x = direction;
transform.localScale = theScale;
}
}
If this doesn't work it's because you've set something up wrong on the Unity side. Note that left may be right and vice versa. Play around with the values passed to SetDirection() if that is the case.
It worked, dude! God bless you, thank you so much!! Really!!
Answer by Fubiou · Sep 07, 2015 at 07:30 AM
Hey, I just found this way, it is simple and works like a charm!
transform.localEulerAngles = transform.eulerAngles + Vector3(0,180,-2*transform.eulerAngles.z);
Thank you! But what am I supposed to do? Add it or use this one ins$$anonymous$$d of all the other code i posted here?
Your answer
Follow this Question
Related Questions
How do I make my player flip to always face the enemy and vice versa? 1 Answer
Flip 2D player in x-axis to face movement direction 5 Answers
Flip the player with arm rotation 2 Answers
2D example: Flip character without moving 0 Answers
2D Character Flip 2 Answers