Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

202
Vistas
Is There a Way to Flip a Sprite in Unity?

I'm working on a 2D Unity project where it's a platformer but you controller the character with gravity. For the game, I need to make it so that when you turn the gravity say, up, it should flip the sprite upside down. This is my code so far in the C# script I have that is attached to the character game object.

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class GravityController2d : MonoBehaviour
{
enum GravityDirection { Down, Left, Up, Right };
public Animator animator;
public GameObject Game_object;
private Vector3 chestPos = new Vector3(6.69f, 1.45f, 0.0f);

void Start()
{
    Physics2D.gravity = new Vector2(0f, -9.8f);
}

void FixedUpdate()
{   
    if (Input.GetKeyDown(KeyCode.DownArrow))
    {
        Physics2D.gravity = new Vector2(0f, -9.8f);
        //flip
    }

    if (Input.GetKeyDown(KeyCode.LeftArrow))
        {
            Physics2D.gravity = new Vector2(-9.8f, 0f);
            //flip
        }
    
    if (Input.GetKeyDown(KeyCode.UpArrow))
        {
            Physics2D.gravity = new Vector2(0f, 9.8f);
            //flip
        }

    if (Input.GetKeyDown(KeyCode.RightArrow))
        {
            Physics2D.gravity = new Vector2(9.8f, 0f);
            //flip
        }

    
} 
}

Edit: The tag I used was Unity2D but it auto corrected it to unity3d so thats my excuse for that.

Also: It needs to also be able to flip 90 degrees in case the player switches the gravity to go to the left/right

9 months ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Assuming you are referring to a SpriteRenderer you can use SpriteRenderer.flipX and SpriteRenderer.flipY and check in which direction your gravity goes like e.g.

// Link in the Inspector
[SerializeField] SpriteRenderer spriteRenderer;

and then

private void UpdateSpriteFlip()
{
    // The conditions according to your needs of course
    spriteRenderer.flipX = Physics2D.gravity.x < 0;
    spriteRenderer.flipY = Physics2D.gravity.y > 0;
}
9 months ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos