在Unity中实现简易的摇杆效果

该代码示例展示了如何在Unity3D中通过`GameTouch`类实现手写摇杆功能,利用`IDragHandler`等接口处理拖动事件,控制角色的移动和旋转。`Cube`类更新函数中应用了摇杆偏移来调整物体的位置和旋转角度,同时大圆限制了移动的范围。
摘要由CSDN通过智能技术生成

除了在使用Eath Touch插件之外,可以进行手写摇杆,一个建议的摇杆也可以实现人物的移动

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

public class GameTouch : MonoBehaviour,IDragHandler,IEndDragHandler,IBeginDragHandler
{
    public static Vector2 offest;
    private Vector2 startPos;

    public void OnBeginDrag(PointerEventData eventData)
    {
        startPos = transform.position;
    }

    public void OnDrag(PointerEventData eventData)
    {
        offest = eventData.position - startPos;
        transform.position = Vector2.ClampMagnitude(offest, 30) + startPos;
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        offest=Vector2.zero;
        transform.position = startPos;
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Cube : MonoBehaviour
{
    // Update is called once per frame
    void Update()
    {
        transform.Translate(GameTouch.offest.y*Time.deltaTime*0.1f*Vector3.forward);
        transform.Rotate(GameTouch.offest.x*Time.deltaTime*0.2f*Vector3.up);
    }
}

在这里插入图片描述三个Image组成,第一个半透明的图片 可有可无 第二个为大圆,用来限制的移动的半径,最后一个是中心,用来控制人物的移动

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值