cocos移动

3 篇文章 0 订阅

//移动ts脚本
export interface ITouchUser {
rightEvent(dir: string): void;
leftEvent(dir: string): void;
}
export class TouchController {
target: cc.Node;
isAllowTouch: boolean = true; //允许移动
startPoint: any;
endPoint: any;
movePoint: any;
minLength: number; //滑动的距离

user: ITouchUser;
constructor(node: cc.Node, user: ITouchUser, minlength: number) {
    this.target = node;
    this.user = user;
    this.minLength = minlength;
    this.addEventHandler();
}
setAllowTouch(isallow: boolean) {
    this.isAllowTouch = isallow;
}
// 用来处理事件监听 方向判断
addEventHandler() {
    // bg 用来创建维护根节点 背景
    // 箭头函数 this的问题
    // Node.on 在节点上注册指定类型的回调函数,也可以设置 target 用于绑定响应函数的 this 对象。

    // touchstart 当手指触摸到屏幕时
    this.target.on('touchstart', (event) => {
        if (!this.isAllowTouch) return;
        // Touch.getLocation 获取当前触点位置。Touch封装了触摸相关的信息。
        // 先取出起始节点  event.getLocation拿到了触摸开始事件对应的位置
        this.startPoint = event.getLocation();
    });
    //touchend 当手指在目标节点区域内离开屏幕时。 */
    this.target.on('touchend', (event) => {
        if (!this.isAllowTouch) return;
        this.touchEnd(event);
    });

    this.target.on('touchmove', (event) => {
        if (!this.isAllowTouch) return;
        this.touchMove(event);
    });
    //touchcancel 当手指在目标节点区域外离开屏幕时
    this.target.on('touchcancel', (event) => {
        if (!this.isAllowTouch) return;
        this.touchEnd(event);
    });

}

touchEnd(event) {
    // 拿到结束的节点
    this.endPoint = event.getLocation();
}
touchMove(event) {
    // 拿到滑动过程坐标
    this.movePoint = event.getLocation();
    this.finishUserMove();
}

finishUserMove() {
    // sub 向量减法,并返回新结果。
    let vec = this.movePoint.sub(this.startPoint);
    // 设置长度才去执行响应
    // 计算两点之间的向量及其模长:cc.pSub(p1, p2) 从 v2.0 开始被废弃,目前最新的替代方法是:p1.sub(p2);

    // 2,两个点的距离计算:cc.pLength(p)
    // 改为:p.mag()
    if (vec.mag(vec) > this.minLength) {
        // 水平方向
        if (vec.x > 0) {
            console.log("向右滑动操作");
            this.user.rightEvent("RIGHT");
        } else {
            this.user.rightEvent("LEFT");
        }

    }
}
destroy() {
    this.target.off("touchstart");
    this.target.off("touchend");
    this.target.off("touchmove");
    this.target.off("touchcancel");
}

}

//调用
import { ITouchUser, TouchController } from “./TouchController”;

//要让你那个脚本 实现接口 export default class Band implements ITouchUser

touchController: TouchController;
构造函数里

this.touchController = new TouchController(this.mobile.mobileBgNode, this, 80);//参数1为哪个身上移动,参数2为谁移动 ,参数3为判断滑动距离

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值