美文网首页
控制角色行动(+虚拟杆NGUI)

控制角色行动(+虚拟杆NGUI)

作者: 怎么可以这么 | 来源:发表于2018-05-27 18:34 被阅读0次

方法一:

摄像机:

private Transform player;

    public float speed = 2;

void Start () {

        player = GameObject.FindGameObjectWithTag(Tags.player).transform;

}

void Update () {

        //添加的Vector视情况而定

        Vector3 targetPos = player.position + new Vector3(0,2.42f,-2.42f);

        transform.position = Vector3.Lerp(transform.position,targetPos,speed*Time.deltaTime);

        //一直注视着角色

        Quaternion targetRotation= Quaternion.LookRotation(player.position-transform.position);

        //弧度(角度)

        transform.rotation = Quaternion.Slerp(transform.rotation,targetRotation,speed*Time.deltaTime);

}

人物:

private CharacterController cc;

public float speed = 3;

void Awake() { cc = this.GetComponent();}

void Update () {

        float h = Input.GetAxis("Horizontal");

        float v = Input.GetAxis("Vertical");

//以虚拟杆的值为优先

        if (Joystick.h!=0||Joystick.v!=0)

        {

            h = Joystick.h;v = Joystick.v;

        }

        if (h!=0||v!=0){

            Vector3 targetDir = new Vector3(h, 0, v);

            transform.LookAt(targetDir+transform.position);

            cc.SimpleMove(targetDir * speed);

        }

}

方法二:

用NGUI制作虚拟杆:

private bool isPress=false;

    private Transform button;

    //移动边界

    public float boundary=73;

    public static float v =0;

    public static float h = 0;

    //判断是否有按键动作

    void OnPress(bool isPress) {

        this. isPress = isPress;

        if (!isPress)

        {

            button.localPosition = Vector2.zero;

        }

        h = 0; v = 0;

    }

    void Awake() {

        button = transform.Find("Button");

    }

void Update () {

        if (isPress)

        {

            //UICamera.lastEventPosition获取的是像数值

            //取中心点位置

            Vector2 touchPos = UICamera.lastEventPosition;

            touchPos -= new Vector2(91,91);

            //把触摸位置设置给button,并固定移动范围

            float distance = Vector2.Distance(Vector2.zero,touchPos);

            if (distance > boundary)

            {

                touchPos = touchPos.normalized * boundary;

                button.localPosition = touchPos;

            }

            else { button.localPosition = touchPos; }

            v = touchPos.y/ boundary;

            h = touchPos.x/ boundary;

        }

}

相关文章

网友评论

      本文标题:控制角色行动(+虚拟杆NGUI)

      本文链接:https://www.haomeiwen.com/subject/vcqijftx.html