简体   繁体   English

从右向左移动时Unity 2D敌人移动脚本不会翻转

[英]Unity 2D enemy movement script not flipping when moving right to left

I'm trying to write a script for my enemy movements. 我正在尝试为我的敌人的动作编写脚本。 Here is my code: 这是我的代码:

public class EnemiesMovement : MonoBehaviour
{
     private bool isFacingRight = false;
     public float speed = 10f;
     private float startPoint;
     private float endPoint;
     public float unitMovement = 2f;
     private Rigidbody2D enemy;
     private Animator anim;
     bool moveRight;
// Start is called before the first frame update
     void Start()
     {
         enemy = GetComponent<Rigidbody2D>();
         anim = GetComponent<Animator>();
         startPoint = enemy.position.x;
         endPoint = startPoint + unitMovement;
     }

// Update is called once per frame
     void Update()
     {
         if (enemy.position.x >= endPoint)
             moveRight = false;

         if (enemy.position.x <= startPoint)
             moveRight = true;

         if (moveRight)
         {
             enemy.velocity = new Vector2(-transform.localScale.x, 0) * speed;
             if (!isFacingRight)
            Flip();
         }

         if (!moveRight)
         {
             enemy.velocity = new Vector2(transform.localScale.x, 0) * speed;
             if (isFacingRight)
                 Flip();
         }
     }

     void Flip()
     {
         isFacingRight = !isFacingRight;
         Vector3 scale = transform.localScale;
         scale.x *= -1;
         transform.localScale = scale;
     }
}

The movement of the enemy is right, but after the enemy flips its sprites, it doesn't change the direction of its movement. 敌人的移动是正确的,但是在敌人翻转其精灵后,它不会改变其移动方向。 Basically, it continues to the right, even though its sprite has turned left. 基本上,它会继续向右移动,即使其精灵已经向左转。 Can someone show me how I can fix this? 有人可以告诉我如何解决此问题吗?

My enemy spite has a positive scale facing to the left. 我的敌人尽管朝左有正面的比例尺。

Velocity is affected by the scale property. 速度受缩放属性的影响。

So if you change the scale negative, everything on this GameObject flips, it's not necessary to change the velocity direction. 因此,如果将比例缩放更改为负数,则GameObject上的所有内容都将翻转,因此无需更改速度方向。

Are you getting bewildered? 你感到困惑吗? You can try another method to flip the sprite. 您可以尝试另一种翻转精灵的方法。

GetComponent<SpriteRenderer>().flipX = true;

This only flips the sprite renderer, other things are working as normal in its world space. 这只会翻转精灵渲染器,其他东西在其世界空间中仍能正常工作。


Another suggests as Unity documented it's better to change Rigidbody's property in the FixedUpdate . 正如Unity记录的那样,另一个建议是最好在FixedUpdate更改Rigidbody的属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM