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
Assuming you are referring to a SpriteRenderer
you can use SpriteRenderer.flipX
and SpriteRenderer.flipY
and check in which direction your gravity goes like eg
// 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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.