CocosCreator Graphics实现跟随手指

cocosCreator版本 3.4.2

先看一下效果吧

代码示例 代码都有注释 请自行查看


import { _decorator, Component, EventTouch, Graphics, Node, UITransform, Vec3, CameraComponent, Button, Color } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('Example')
export class Example extends Component {
    @property(Graphics)
    grp: Graphics = null
    camera: CameraComponent = null;
    protected onLoad(): void {
        //设置线条宽度
        this.grp.lineWidth = 10;
        this.camera = UIMgr.instance.Camera;
    }

    start() {
        //监听手指事件
        this.grp.node.on(Node.EventType.TOUCH_START, this.startgarphics.bind(this))
        this.grp.node.on(Node.EventType.TOUCH_MOVE, this.movegarphics.bind(this))
        this.grp.node.on(Node.EventType.TOUCH_CANCEL, this.endgarphics.bind(this))
        this.grp.node.on(Node.EventType.TOUCH_END, this.endgarphics.bind(this))
    }

    //手指松开
    endgarphics(event) {
        //关闭画图
        this.grp.close()
    }

    //手指按下
    startgarphics(event: EventTouch) {
        //获取手指位置
        let point = event.getLocation()
        //将手指位置转为相机下的世界坐标
        let point1 = this.camera.screenToWorld(new Vec3(point.x, point.y));
        //将世界坐标转为Node节点下的局部坐标
        let touchPoint = this.node.getComponent(UITransform).convertToNodeSpaceAR(point1);
        //把路径移动到画布中的指定点,不创建线条
        this.grp.moveTo(touchPoint.x, touchPoint.y)
    }

    //开始移动
    movegarphics(event: EventTouch) {
        //获取手指位置
        let point = event.getLocation()
        //将手指位置转为相机下的世界坐标
        let point1 = this.camera.screenToWorld(new Vec3(point.x, point.y));
        //将世界坐标转为Node节点下的局部坐标
        let touchPoint = this.node.getComponent(UITransform).convertToNodeSpaceAR(point1);
        //添加一个新点,然后在画布中创建从该点到最后指定点的线条
        this.grp.lineTo(touchPoint.x, touchPoint.y)
        //绘制已定义的路径
        this.grp.stroke()
        //重新规划路径
        this.grp.moveTo(touchPoint.x, touchPoint.y)
    }
}

也可以指定颜色 代码如下

    //设置线条绘制颜色为红色
    red() {
        this.grp.strokeColor = Color.RED
    }

    //设置线条绘制颜色为蓝色
    blue() {
        this.grp.strokeColor = Color.BLUE
    }

 效果如下

如下是节点路径 以及代码挂载

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小张不爱写代码

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值