当前位置: 移动技术网 > IT编程>开发语言>c# > Unity3D实现虚拟按钮控制人物移动效果

Unity3D实现虚拟按钮控制人物移动效果

2019年07月18日  | 移动技术网IT编程  | 我要评论

本文为大家分享了unity3d实现虚拟按钮控制人物移动的具体代码,供大家参考,具体内容如下

创建image的ui组件,在image下新建一个button按钮。在image 和button上拖进sprite图片

在button按钮上挂载该脚本

using system.collections;
using unityengine;
using unityengine.eventsystems;
using unityengine.ui;
 
public class myjoystick : monobehaviour, ipointerdownhandler, ipointeruphandler {
 
  public canvas canvas;
  public static float h;   //h和v的值传回给player脚本,使得物体移动
  public static float v;
 
  private bool ispress = false; //button按钮是否按下
  private vector2 touchpos = vector2.zero; //按下的位置
 
  void update() {
    if (ispress)
    {
      recttransformutility.screenpointtolocalpointinrectangle(canvas.transform as recttransform,
        input.mouseposition, null, out touchpos);
 
      //根据canvas和image的rectransform位置相减得出
      touchpos += new vector2(427, 299); 
 
      float distance = vector2.distance(vector2.zero, touchpos);
 
      if (distance > 52) { //限制button不能超出image位置(两者位置相减得出52)
        touchpos = touchpos.normalized*52;
        transform.localposition = touchpos;
      }
      else
      {
        transform.localposition = touchpos;
      }
 
      h = touchpos.x / 52;
      v = touchpos.y / 52;
    }
 
  }
 
  //鼠标按下时触发
  public void onpointerdown(pointereventdata eventdata) {
    ispress = true;
  }
 
  //鼠标按键弹起时触发
  public void onpointerup(pointereventdata eventdata)
  {
    ispress = false;
    transform.localposition = vector3.zero;
  }
 
}

在玩家身上挂载控制玩家移动的脚本

using system.collections;
using system.collections.generic;
using unityengine;
 
public class playermove : monobehaviour {
 
  public float speed = 0.1f;
 
  private float h = 0;
  private float v = 0;
 
  void update() {
    //首先检测虚拟按键有没有移动,没有再选择键盘输入
    if (mathf.abs(myjoystick.h) > 0 || mathf.abs(myjoystick.v) > 0) {
      h = myjoystick.h;
      v = myjoystick.v;
    }
    else{
      h = input.getaxis("horizontal");
      v = input.getaxis("vertical");
    }
    //玩家位置移动
    if (mathf.abs(h) > 0.1 || mathf.abs(v) > 0.1) {
      vector3 targetdir = new vector3(h, 0, v);
      transform.position += targetdir * speed;
 
      transform.lookat(transform.position+targetdir);
    }
    
  }
}

这样,就能通过按下button来控制玩家移动了。

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网