1. 程式人生 > >使用CharacterController控制行走(包括鍵盤和虛擬槓)

使用CharacterController控制行走(包括鍵盤和虛擬槓)

使用CharacterController控制行走: 使用Input.GetAxis("Horizontal") 和 "Vertical"得到垂直和水平方向的值 使用CharacterController.SimpleMove(Vector3)引數表示運動的方向和速度單位可以認為是 m/s 首先,調出CharacterController並設定
接著設定一個控制Player的指令碼;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMove : MonoBehaviour {


    public float speed = 3;
    private CharacterController cc;

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

	
	// Update is called once per frame
	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 (Mathf.Abs(h) > 0.1f || Mathf.Abs(v) > 0.1f)
        {
            Vector3 targetDir = new Vector3(h, 0, v);
            transform.LookAt(targetDir + transform.position);
            cc.SimpleMove(transform.forward * speed);
        }
	}
}


下面設定虛擬槓來操作,首先通過NGUI設定一個Backgroup, 再設定一個名為Joystick,在Joystick下創造一個child,再在這之下設定一個Box  Collider。
再設計指令碼c#為:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Joystick : MonoBehaviour {

    private bool isPress = false;
    private Transform button;
    public static float h = 0;
    public static float v = 0;
    void Awake()
    {
        button =transform.Find("Button");
    }
    void OnPress(bool isPress)
    {
        this.isPress = isPress;
        button.localPosition =Vector3.zero;
        h = 0;
        v = 0;
    }

    void Update()
    {
        if (isPress)
        {
            Vector2 touchPos = UICamera.lastTouchPosition;
            touchPos -= new Vector2(91, 91);
            float distance = Vector2.Distance(Vector2.zero, touchPos);
            if (distance > 73)
            {
                touchPos = touchPos.normalized * 73;
                button.localPosition = touchPos;
            }
            else
            {
                button.localPosition = touchPos;
            }

            h = touchPos.x / 73;
            v = touchPos.y / 73;
        }
        
    }
}