首页 > 解决方案 > Unity 2D 旋转 AI 敌人看玩家

问题描述

我正在制作一个左右两侧的 2D 游戏,因此玩家只能向左或向右移动或跳跃。我做了一个AI作为敌人。人工智能工作正常。他可以去找玩家杀死他。

问题是当他去杀死他时敌人不能旋转或面对玩家。我想让 AI 看着玩家。当玩家在敌人的左边时,敌人应该旋转到左边看玩家。我搜索了许多网站,但没有得到任何正确的解决方案。这是我的敌人脚本:

public class enemy : MonoBehaviour
{
    public float speed;
    private Animator animvar;
    private Transform target;
    public GameObject effect;
    public float distance;
    private bool movingRight = true;
    public Transform groundedDetection;
    public float moveInput;
    public bool facingRight = true;

    void Start()
    {
        animvar = GetComponent<Animator>();
        target = GameObject.FindGameObjectWithTag("Player").transform;
    }

    // Update is called once per frame
    void Update()
    {
        if (Vector3.Distance(target.position, transform.position) < 20)
        {
            transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
        }
        else
        {
            transform.Translate(Vector2.right * speed * Time.deltaTime);
        }
        RaycastHit2D groundInfo = Physics2D.Raycast(groundedDetection.position, Vector2.down, distance);
    }

    void OnCollisionEnter2D(Collision2D col)
    {
        if (col.gameObject.tag.Equals("danger"))
        {
            Instantiate(effect, transform.position, Quaternion.identity);
            Destroy(gameObject);
        }
        if (col.gameObject.tag.Equals("Player"))
        {
            Instantiate(effect, transform.position, Quaternion.identity);
            Destroy(gameObject);
        }
    }
}

游戏是 2D,左,右,使用 Unity3D 跳跃。

标签: c#unity3d2d

解决方案


你需要一个可以翻转你的精灵的函数,你可以通过改变变换的比例来做到这一点,并保持一个布尔值来检查它面对的地方 bool facingRight;,所以像这样

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

并在您的Update检查中是否需要翻转

if (Vector3.Distance(target.position,transform.position)<20)
    {

     transform.position=Vector2.MoveTowards(transform.position, target.position,speed*Time.deltaTime);
     if(target.position.x > transform.position.x && !facingRight) //if the target is to the right of enemy and the enemy is not facing right
        Flip();
     if(target.position.x < transform.position.x && facingRight)
        Flip();
   }

推荐阅读