2d character conditionally walking backwards or flipping
Hi,
I'm trying to build a platformer where the character can face left and right while his sword is sheathed, and only face right, (walking backwards to left if needed) when he has it's drawn. Instead he either doesn't care if the sword is drawn or just doesn't flip at all. All help appreciated.
The code i used is like below:
public class playerMovement : MonoBehaviour {
public float maxSpeed = 1.5f;
bool facingRight = true;
bool drawsword = false;
void Start () {
anim = GetComponent<Animator> ();
rb2D = GetComponent<Rigidbody2D> ();
}
void FixedUpdate ()
{
float move = Input.GetAxis ("Horizontal");
rb2D.velocity = new Vector2 (move * maxSpeed, rb2D.velocity.y);
bool drawsword = Input.GetButtonDown ("Fire1");
if (drawsword) {
anim.SetBool ("drawsword", true);
}
if (drawsword = true && Input.GetKeyDown (KeyCode.R)) {
anim.SetBool ("drawsword", false);
if (drawsword = false && move > 0 && !facingRight)
Flip ();
else if (drawsword = false && move < 0 && facingRight)
Flip ();
}
void Flip ()
{
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
Comment
Answer by Leviath · Jan 02, 2019 at 11:49 AM
I guess the problem is much more complicated than it looks. I've completely removed the flip () function to overcome this issue and made mirrored sprites for walking left and walking backwards towards left.
Answer by Mister-Dighel · Jan 02, 2019 at 05:42 PM
You have to pass the Horizontal input to the Flip function, try Flip(move). using UnityEngine;
public class Move : MonoBehaviour
{
private float x;
private bool right;
void Update()
{
x = Input.GetAxis("Horizontal");
transform.Translate(x*0.05f, 0, 0);
Flip(x);
}
private void Flip(float Horizontal){
if(Horizontal>0 && right || Horizontal<0 && !right){
right = !right;
Vector3 scale = transform.localScale;
scale.x *=-1;
transform.localScale = scale;
}
}
}