【Unity3D】控制角色移动 键盘按键与虚拟摇杆

2020/02/28

先上角色移动脚本

using UnityEngine;
using System.Collections;

public class PlayerMove:MonoBehaviour
{
   private CharacterController cc;
   public float speed=4;
   
   void Awake()
   {
       cc=this.GetComponent<CharacterController>();
   }

   void Update()
   {
      float h=Input.GetAxis("Horizontal");
      float v=Input.GetAxis("Vertical");

      if(Mathf.Abs(h) >0.1f || Maathf.Abs(v> >0.1f)
      {
          Vector3 targetDir = new Vector3(h,0,v);
          transform.LookAt(targetDirr +transform.position);
          cc.SimpleMove(transform.forward *speed);
      }
   }
}

然后是虚拟摇杆的代码

using UnityEngine;
using System.Collections;

public class Joystick:MonoBehaviour
{
	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;
		v=0;
		h=0;
	}
	void Update()
	{
		if(isPress)
		{
			Vector2 touchPos=UICamera.lastTouchPosition;
			touchPos -=new Vector2(91,91);
			float distance =Vector2.Distance(Vector2.zero,touchPos);
			if(distance >73)
			{
				touchPos=touchPos.normalized *73;
				button.localPosition =touchPos;
			}
			else
			{
				button.localPositon =touchPos;
			}
			h=touchPos.x /73;
			v=touchPos.y /73;
		}
	}
}

最后是键盘和虚拟摇杆的结合 其实很简单 只需要修改这一段代码就行了

void Update()
   {
      float h=Input.GetAxis("Horizontal");
      float v=Input.GetAxis("Vertical");

      if(Mathf.Abs(h) >0.1f || Maathf.Abs(v> >0.1f)
      {
          Vector3 targetDir = new Vector3(h,0,v);
          transform.LookAt(targetDirr +transform.position);
          cc.SimpleMove(transform.forward *speed);
      }
   }

修改成

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 || Maathf.Abs(v> >0.1f)
      {
          Vector3 targetDir = new Vector3(h,0,v);
          transform.LookAt(targetDirr +transform.position);
          cc.SimpleMove(transform.forward *speed);
      }
   }

(转载本站文章请注明作者和出处 恬静的小魔龙

Show Disqus Comments

Post Directory

扫码或搜索:沉默王二
发送 290992
即可立即永久解锁本站全部文章