Unity_虚拟摇杆的实现_065

本文介绍了一个Unity游戏开发中使用的摇杆控制器脚本。该脚本实现了通过拖拽操作来控制游戏角色移动方向的功能,并限制了摇杆的最大拖动距离。同时,脚本还包含了如何在拖拽结束时复位摇杆位置的方法。

设置摇杆的背景图片的锚点如下:
这里写图片描述

设置摇杆的锚点为背景图片的中心点。
并给摇杆绑定脚本如下:

using UnityEngine;
using UnityEngine.EventSystems;
using System.Collections;
using System;

public class JoyStickController : MonoBehaviour,IDragHandler,IEndDragHandler {
    //最大的拖动距离
    public float maxDragDistance = 50f;
    //虚拟摇杆的方向
    public Vector3 direction;
    //玩家
    public GameObject player;
    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        //屏幕上的y轴分量 当作游戏世界里的z分量
        //设置玩家的朝向
        player.transform.forward = new Vector3(direction.x,0,direction.y);
        int flag = Vector3.Distance(Vector3.zero, this.transform.localPosition) <1f ? 0 : 1;
        player.transform.Translate(Vector3.forward * flag * Time.deltaTime,Space.Self);

    }
    //拖拽中的时候
    public void OnDrag(PointerEventData eventData)
    {
        this.transform.position = Input.mousePosition;
        if (Vector3.Distance(Vector3.zero,this.transform.localPosition) > maxDragDistance)
        {
            direction = this.transform.position - Vector3.zero;
            this.transform.localPosition = direction.normalized * maxDragDistance;
        }
    }
    //拖拽结束的时候
    public void OnEndDrag(PointerEventData eventData)
    {
        this.transform.localPosition = Vector3.zero;
    }
}

这里写图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yy763496668

您的鼓励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值