您的位置:首页 > 移动开发 > Unity3D

【开发笔记】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);
}
}
}
阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: