当我翻转我的精灵时,它会离开瓷砖贴图的前景



我遇到了一个无法解决的问题。每当我移动角色时,如果它靠近贴图的边缘,它就会通过瓷砖贴图碰撞器并离开贴图。这是我拍的截图:

这是正常的:链接文本

这是错误发生的时候:错误

这是我用来移动和翻转角色的代码:

using System.Collections;
using UnityEngine;
using UnityEngine.InputSystem;

public class MovementScript : MonoBehaviour
{
Vector2 moveInput;

Animator animator;
Rigidbody2D rb;
BoxCollider2D myCollider;
PlayerStats playerStats;
float playerSpeed;

[SerializeField] float timeToWaitAfterBeingAttackedToMoveAgain = 1f;
[SerializeField] int kickbackFromEnemyAttack = 40;

void Start()
{
myCollider = GetComponent<BoxCollider2D>();
rb = GetComponent<Rigidbody2D>();
animator = GetComponent<Animator>();
playerStats = GetComponent<PlayerStats>();
}

void FixedUpdate()
{
playerSpeed = playerStats.GetPlayerSpeed();
if(playerStats.PlayerIsAlive())
{
Run();
FlipSprite();
}        
}

//If the player goes left the sprite flips left, otherwise it flips to the right
void FlipSprite()
{
bool playerHasHorizontalSpeed = Mathf.Abs(rb.velocity.x) >= Mathf.Epsilon;

if(playerHasHorizontalSpeed)
{
transform.localScale = new Vector2(Mathf.Sign(rb.velocity.x), 1f);
}
}

void Run()
{        
Vector2 playerVelocity = new(moveInput.x * playerSpeed, rb.velocity.y);
rb.velocity = playerVelocity;

if (myCollider.IsTouchingLayers(LayerMask.GetMask("Ground")))
{
animator.SetBool("run", Mathf.Abs(rb.velocity.x) >= Mathf.Epsilon);
}   
}

void OnMove(InputValue value)
{
moveInput = value.Get<Vector2>();
}     

private void OnCollisionEnter2D(Collision2D collision)
{
if(collision.gameObject.CompareTag("Enemy") && playerStats.PlayerIsAlive())
{            
this.enabled = false;
TriggerKickup();
StartCoroutine(ActivateMovement());
}
}
}

您最好获取SpriteRenderer组件并更改其flipX属性,而不是反转比例。

无论哪种方式,如果在翻转精灵时精灵以意外的方式移动,则很可能枢轴没有按您想要的方式设置——例如,在这种情况下,它可能设置在精灵的左下角。

选择精灵资源,单击检查器中的"精灵编辑器",然后将精灵的轴设置为中间或中间底部。应用更改,精灵应该从中心而不是从边缘翻转。

最新更新