当前位置: 移动技术网 > IT编程>开发语言>c# > Unity实现虚拟摇杆效果

Unity实现虚拟摇杆效果

2020年06月23日  | 移动技术网IT编程  | 我要评论
本文实例为大家分享了unity实现虚拟摇杆效果的具体代码,供大家参考,具体内容如下首先添加两者图片从左到右分别是back和front将front放到back中心 在front身上添加脚本using s

本文实例为大家分享了unity实现虚拟摇杆效果的具体代码,供大家参考,具体内容如下

首先添加两者图片

从左到右分别是back和front

将front放到back中心
在front身上添加脚本

using system.collections;
using system.collections.generic;
using unityengine;
using unityengine.eventsystems;//导入命名空间

public class joystick : monobehaviour,ipointerdownhandler,ipointeruphandler {//实现接口

 private bool istouched = false;//标志位,用于标示值是否拖拽按钮
 private static float h = 0;
 private static float v = 0;//这两者用于表示水平(竖直)方向按钮移动的值,相当于通过input.getaxis("horizontal");input.getaxis("vertical");
 [serializefield] private vector2 joystickpivot;//按钮中心位置在世界坐标中的值
 [serializefield] private float radius;//按钮的半径(决定了按钮的活动范围)

 // update is called once per frame
 void update () {
 if (istouched)
 {
  vector2 moupos = input.mouseposition;
  moupos -= joystickpivot;//将鼠标位置转换为本地坐标
  if (vector2.distance(moupos,vector2.zero)>=radius)//如果鼠标移动超出范围,将图片放到边缘
  {
  moupos = moupos.normalized*radius;
  }
  transform.localposition = moupos;
  h = moupos.x/radius;
  v = moupos.y/radius;

 }
 }

 public void onpointerdown(pointereventdata eventdata)
 {
 istouched = true;
 }

 public void onpointerup(pointereventdata eventdata)
 {
 istouched = false;
 h = 0;
 v = 0;//不拖拽时二者为0
 transform.localposition = vector3.zero;//让按钮返回中心魏智
 }
}

对于代码中的h,v就是我们操作遥感时水平(竖直)方向获取的值(0-1),其他脚本获取这两个静态变量的值就可以实现对自身物体的移动了。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网