【开发笔记】unity 制作简易摇杆并控制物体移动
2018-12-20 10:18
706 查看
项目开发中,有时候为了优化项目,不得不抛弃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); } } }阅读更多
相关文章推荐
- 我的Unity(10)一点一滴 利用UI制作摇杆控制物体移动
- Unity摇杆控制物体移动c#脚本
- 【小松教你手游开发】【unity实用技能】unity3d 陀螺仪控制camera移动旋转
- unity开发(一个按钮控制不同的物体)
- unity 实现键盘控制物体移动和转向
- PHP移动互联网开发笔记(3)——运算符与流程控制
- 游戏开发学习笔记(四)虚拟摇杆的制作
- android开发笔记————简易随机器的制作
- Unity 3D 控制物体上下左右均匀移动脚本
- Unity 3D 控制物体前后左右均匀移动脚本
- 面向组件编程之Unity 7.怎样脚本控制物体旋转和移动 关键字:画圆&&Translate/transform.Translate,transform.Rotate
- unity学习笔记之物体移动
- unity实现3d摇杆 结合leapmotion控制实现VR场景移动
- Unity2D - 4. 实现android虚拟摇杆控制人物移动
- Layabox 3D游戏开发学习笔记---射线检测,鼠标控制物体运动
- Unity简单利用屏幕坐标转换实现鼠标控制物体移动
- unity中控制物体的移动,和旋转
- Android开发笔记之简易画画板的制作
- Unity 控制物体移动 旋转 缩放
- Unity 碰撞检测,触发检测,方向键控制物体移动