[英]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.我正在开发一个 2D Unity 项目,它是一个平台游戏,但你 controller 是具有重力的角色。 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.
到目前为止,这是我在 C# 脚本中的代码,该脚本附加到角色游戏 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.编辑:我使用的标签是 Unity2D,但它自动将其更正为 unity3d 所以这就是我的借口。
Also: It needs to also be able to flip 90 degrees in case the player switches the gravity to go to the left/right另外:它还需要能够翻转 90 度,以防玩家将重力切换到左/右 go
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假设您指的是
SpriteRenderer
,您可以使用SpriteRenderer.flipX
和SpriteRenderer.flipY
并检查您的重力方向,例如
// 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.