0

嘿,我正在统一制作一个自上而下的游戏。我遇到的问题是让 npc 玩家在跟随玩家时改变他们面对的方式。因此,如果玩家向左转,npc 会跟随他们,但不会转身面对 npc 前进的方向。我可以让 npc 看起来像在走路,只是不改变它的方向。这是一个 2d 自上而下的游戏,请任何帮助都会很好。这是我的NPC代码。

using UnityEngine;
using System.Collections;

public class SlimeController : MonoBehaviour
{

public Transform Character; // Target Object to follow
public float speed = 0.1F; // Enemy speed
public float maxDist = 10.0f;
public float attackdistance = 3;
public float farenough;
private Vector3 directionOfCharacter;
private bool challenged = false;// If the enemy is Challenged to follow by the player
public Transform StartMarker;
private Vector3 goback;
public Transform EndMarker;
public Rigidbody2D rb;
Animator anim;
float oldx;
bool left;
bool right;

private void Start()
{
    rb = GetComponent<Rigidbody2D>();
    anim= GetComponent<Animator>();
    oldx = transform.position.x;

}



void Update()
{
    anim.SetBool("left", false);
    anim.SetBool("right", false);
    var distanceFromPlayer = Vector3.Distance(Character.position, transform.position);

    if(oldx>transform.position.x)
    {
        left = false;
        right = true;
    }

    if(oldx<transform.position.x)
    {
        left = true;
        right = false;
    }
    if (oldx == transform.position.x)
    {
        left = false;
        right = false;
    }

    if (challenged)
    {

        directionOfCharacter = Character.transform.position - transform.position;
        directionOfCharacter = directionOfCharacter.normalized;    // Get Direction to Move Towardsss
        transform.Translate(directionOfCharacter * speed, Space.World);
        enabled = true;




        if (distanceFromPlayer < attackdistance)
        {

            attack();
        }

        if (distanceFromPlayer > attackdistance)
        {
            speed = 0.03f;
        }


    }

    if (!challenged)
    {

        goback = StartMarker.transform.position - transform.position;
        goback = goback.normalized;
        transform.Translate(goback * speed, Space.World);

    }
}

// Will be triggered as soon as player would touch the Enemy Object
void OnTriggerEnter2D(Collider2D other)
{
    if (other.gameObject.name == ("Player"))
    {
        challenged = true;

    }
}

private void OnTriggerExit2D(Collider2D other)
{
    if (other.gameObject.name == ("Player"))
    {
        speed = 0.03f;
        challenged = false;
    }

}

void attack()
{
    speed = 0;
    transform.Translate(directionOfCharacter * speed, Space.World);
}

}

4

1 回答 1

1

这是因为您只是将对象移向目标。但是要让它看到您的目标,您还需要沿目标方向旋转它。

Transform 组件有一个名为 的函数LookAt。你为它提供你的目标和你的对象应该旋转的轴。所以在你的情况下:

this.transform.LookAt(Character, Vector3.up);

有关更多信息,请参见此处LookAt

于 2017-01-14T22:29:53.137 回答