欢迎来到代码驿站!

.NET代码

当前位置:首页 > 软件编程 > .NET代码

Unity实现虚拟摇杆效果

时间:2021-04-23 09:26:43|栏目:.NET代码|点击:

本文实例为大家分享了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),其他脚本获取这两个静态变量的值就可以实现对自身物体的移动了。

上一篇:C#实现文件压缩与解压的方法示例【ZIP格式】

栏    目:.NET代码

下一篇:C#中 const 和 readonly 的不同

本文标题:Unity实现虚拟摇杆效果

本文地址:http://www.codeinn.net/misctech/106774.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有