So I’m following the 2D platformer tutorial found here:
In the latter part of that video he adds the following code to flip the character when running backwards through the scene like so:
if (Input.GetAxis("Horizontal") < -0.1f)
{
transform.localScale = new Vector3(-1, 1, 1);
}
if (Input.GetAxis("Horizontal") > 0.1f)
{
transform.localScale = new Vector3(1, 1, 1);
}
I get that it finds the direction across the Horizontal axis and then adjusts the transform properties to flip the sprite if necessary but it doesn’t seem to be working for me. The player just ends up moonwalking backwards when tested.
Here’s the full Csharp if needed
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class player : MonoBehaviour {
public float maxSpeed = 15;
public float speed = 50f;
public float jumpPower = 150f;
public bool grounded;
private Animator anim;
private Rigidbody2D rb2d;
// Use this for initialization
void Start () {
rb2d = gameObject.GetComponent<Rigidbody2D>();
anim = gameObject.GetComponent<Animator>();
}
// Update is called once per frame
void Update () {
anim.SetBool("Grounded",grounded);
anim.SetFloat("Speed", Mathf.Abs(Input.GetAxis("Horizontal")));
if (Input.GetAxis("Horizontal") < -0.1f)
{
transform.localScale = new Vector3(-1, 1, 1);
}
if (Input.GetAxis("Horizontal") > 0.1f)
{
transform.localScale = new Vector3(1, 1, 1);
}
}
private void FixedUpdate()
{
float h = Input.GetAxis("Horizontal");
//Moving the player
rb2d.AddForce((Vector2.right * speed) * h);
//Limiting Speed of the player
if (rb2d.velocity.x > maxSpeed)
{
rb2d.velocity = new Vector2(maxSpeed, rb2d.velocity.y);
}
if (rb2d.velocity.x < -maxSpeed)
{
rb2d.velocity = new Vector2(-maxSpeed, rb2d.velocity.y);
}
}
}