cocos creator 2.4.x 画虚线

230 阅读1分钟
private drawDashedLine(start: cc.Vec3, end: cc.Vec3, dashLength: number = 30, color: cc.Color = cc.Color.WHITE) {
        let graphics = this.graphics;
        graphics.clear();
        // 设置线条颜色为红色
        graphics.strokeColor = color;
        graphics.lineWidth = 10;

        let previousPos = start;

        let diffX = end.x - start.x;
        let diffY = end.y - start.y;

        // 计算距离和方向
        let length = Math.sqrt(diffX * diffX + diffY * diffY);
        let directionX = diffX / length;
        let directionY = diffY / length;

        for (let i = 0; i < length; i += dashLength * 2) {
            // 计算当前段的结束点
            let curSegmentEndPos = cc.v3(start.x + directionX * (i + dashLength), start.y + directionY * (i + dashLength));

            if (i + dashLength > length) {
                curSegmentEndPos = end;//如果超过总长度,则最后一段直接到end点。
            }

            graphics.moveTo(previousPos.x, previousPos.y);
            graphics.lineTo(curSegmentEndPos.x, curSegmentEndPos.y);

            previousPos = cc.v3(start.x + directionX * (i + dashLength * 2), start.y + directionY * (i + dashLength * 2));
        }

        // 应用笔触
        graphics.stroke();
    }