【开发笔记】unity 制作简易摇杆并控制物体移动

本文详细介绍如何在Unity中自制摇杆替代Easytouch插件,通过编写自定义脚本来优化内存使用并提升游戏性能。文章提供了具体实现步骤,包括创建图片精灵、编写脚本以及在游戏角色移动中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

首先新建两个图片精灵
在这里插入图片描述
然后在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;
        }

    }

下图是里面各个数值的由来
在这里插入图片描述
然后在玩家移动的脚本里调用摇杆脚本的 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);
        }
	}
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值