Npc动画跟随玩家统一2d自上而下

时间:2017-01-14 16:56:00

标签: c# unity3d topdown

嘿,我正在团结一场自上而下的比赛。我遇到的问题是让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);
}

}

1 个答案:

答案 0 :(得分:1)

这是因为您只是将物体移向目标。但要让它看到你的目标,你需要将其旋转到你的目标方向。

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

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

有关LookAt的详细信息,请参阅here