Unity中的AI脚本。在代码中阻止Y旋转

时间:2017-03-31 07:07:17

标签: unity3d rotation artificial-intelligence

我正在创造一个世界是3D但角色是2D的游戏。这意味着我的Y旋转不能改变,否则2D精灵旋转。我有一个人工智能的脚本,当敌人确实吸引我的玩家时,他也旋转了90度。如何修改我的代码以使sprite在X轴和Z轴上跟随我的播放器,但Y轴旋转保持为零。

//CODE STARTS

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AISimple : MonoBehaviour
{
    public Transform player;
    float distancefrom_player;
    public float look_range = 20.0f;
    public float agro_range = 10.0f;
    public float move_speed = 5.0f;
    public float damping = 6.0f;
    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        distancefrom_player = Vector3.Distance(player.position, transform.position);

        if (distancefrom_player < look_range)
        {
            lookAt();
        }

        if (distancefrom_player < agro_range)

        {
            attack();
        }
    }

    void lookAt()
    {
        Quaternion rotation = Quaternion.LookRotation(player.position - transform.position);
        transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping);
    }

    void attack()
    {
        transform.Translate(Vector3.forward * move_speed * Time.deltaTime);
    }

}

2 个答案:

答案 0 :(得分:0)

刚体具有此功能,如果勾选冻结y旋转,您就可以了

答案 1 :(得分:0)

好的,然后在设置之前尝试修改y旋转

    void lookAt()
    {
        Quaternion rotation = Quaternion.LookRotation(player.position - transform.position);
        var euler = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping).eulerAngles;
        euler.y = 0f;

        transform.rotation = Quaternion.Euler(euler);
    }