c# - C# UNITY 2D 试图在 x 方向翻转精灵
问题描述
我要做的就是当敌人转身时,它的精灵会翻转,下面的代码是我所管理的,但现在它只在两次接近但不是我需要的方向改变后翻转。请帮忙。
[HideInInspector]
public bool facingRight = true;
public float speed;
Rigidbody2D rbody;
public float timer;
Animator anim;
public float directionx;
// Use this for initialization
void Start()
{
rbody = GetComponent<Rigidbody2D>();
StartCoroutine(Move(timer));
}
IEnumerator Move(float timer)
{
while (0 < 1)
{
Vector2 targetVelocity = new Vector2(directionx, 0);
rbody.velocity = targetVelocity * speed;
yield return new WaitForSeconds(timer);
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
Vector2 targetVelocity1 = new Vector2(-directionx, 0);
rbody.velocity = targetVelocity1 * speed;
yield return new WaitForSeconds(timer);
}
}
}
解决方案
该代码非常不言自明,您只需要设置一个变量即可知道玩家开始移动的方向(m_FacingRight
在我的情况下),然后决定何时发生“翻转”调用flipFunction()
:
private bool m_FacingRight = true; // For determining which way the player is currently facing.
private void flipFunction()
{
// Switch the way the player is labelled as facing.
m_FacingRight = !m_FacingRight;
// Multiply the player's x local scale by -1.
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
推荐阅读
- html - 如何在所有浏览器中获得统一的 unicode(HTML 实体)外观
- vb.net - 500k kvps的并发字典(是否删除kvps)
- css - 如何防止图像在较低分辨率下过大?
- c# - 将表格拆分为 PowerPoint 文件中的多张幻灯片
- android - onStop 在 onDestroy 之后被调用?
- javascript - 用于渲染 Dicom 的 vtk.js 和基石交互
- c# - 如何确定使用哪种方法,在 ASP.NET Core 中使用我的自定义属性
- php - 无法获取在 codeigniter 中给定时间之间存在的记录
- javascript - 子状态已更新但未呈现
- azure - Azure Devops kubectl 任务部署映像的状态为 ErrImagePull/ImagePullBackOff