项目开发中,有时候为了优化项目,不得不抛弃Easytouch插件,因为相对来说自己写的摇杆占用内存较小,用起来也更加方便

首先新建两个图片精灵
【开发笔记】unity 制作简易摇杆并控制物体移动
然后在Joystick上挂载下面的脚本

 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;
        if (isPress == false) {
            button.localPosition = Vector3.zero;//鼠标抬起,位置归零
            h = 0; v = 0;
        }
    }

    void Update() {

        if (isPress) {
            //触摸点的位置
            Vector2 touchPos = UICamera.lastTouchPosition;
            //按钮父物体的size为182  所以减去91
            touchPos -= new Vector2(91, 91);//获取中心点的坐标
            float distance = Vector2.Distance(Vector2.zero, touchPos);
            //73==按钮的中心点到它父物体的最远距离
            if (distance > 73) {
                touchPos = touchPos.normalized * 73;
                button.localPosition = touchPos;//中心的按钮坐标跟随鼠标
            } else {
                button.localPosition = touchPos;
            }

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

    }

下图是里面各个数值的由来
【开发笔记】unity 制作简易摇杆并控制物体移动
然后在玩家移动的脚本里调用摇杆脚本的 H V 的偏移量来实现物体移动
玩家移动脚本

public class PlayerMove : MonoBehaviour {

    private CharacterController cc;
    private Animator animator;
    public float speed = 4;

    void Awake() {
        cc = this.GetComponent < CharacterController>();
        animator = this.GetComponent<Animator>();
    }
	
	
	// 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.1) {
            animator.SetBool("Walk", true);
            if (animator.GetCurrentAnimatorStateInfo(0).IsName("PlayerRun")) {
                Vector3 targetDir = new Vector3(h, 0, v);
                transform.LookAt(targetDir + transform.position);
                cc.SimpleMove(transform.forward * speed);
            }
        } else {
            animator.SetBool("Walk", false);
        }
	}
}

相关文章:

  • 2021-12-01
  • 2022-01-13
  • 2021-10-12
  • 2021-05-19
  • 2022-01-25
  • 2021-05-21
  • 2021-10-11
  • 2021-07-20
猜你喜欢
  • 2021-09-04
  • 2022-12-23
  • 2022-01-01
  • 2022-12-23
  • 2021-12-22
  • 2021-08-11
  • 2021-12-31
相关资源
相似解决方案