From c3c17849bf131d41502e7fac8ed968b9ef5da219 Mon Sep 17 00:00:00 2001 From: Jone <350791117@qq.com> Date: Mon, 18 Feb 2019 14:32:07 +0800 Subject: [PATCH] fix scroll-view , editbox and click error --- cocos/3d/ui/components/canvas-component.ts | 67 +++-- .../3d/ui/components/editbox/edit-box-impl.ts | 11 +- cocos/3d/ui/components/layout-component.ts | 21 +- .../3d/ui/components/scroll-bar-component.ts | 132 ++++----- .../3d/ui/components/scroll-view-component.ts | 256 +++++++++--------- cocos/3d/ui/components/slider-component.ts | 5 +- .../ui/components/ui-transfrom-component.ts | 64 +++-- .../3d/ui/components/view-group-component.ts | 2 + cocos/3d/ui/components/widget-component.ts | 24 +- cocos/3d/ui/components/widget-manager.ts | 10 +- cocos/assets/CCSpriteFrame.ts | 2 +- cocos/core/platform/CCView.js | 1 + cocos/renderer/ui/ui.ts | 6 +- 13 files changed, 342 insertions(+), 259 deletions(-) diff --git a/cocos/3d/ui/components/canvas-component.ts b/cocos/3d/ui/components/canvas-component.ts index 499b5f8e92..7d32a69841 100644 --- a/cocos/3d/ui/components/canvas-component.ts +++ b/cocos/3d/ui/components/canvas-component.ts @@ -30,7 +30,10 @@ import { ccclass, executeInEditMode, executionOrder, menu, property } from '../. import { GFXClearFlag } from '../../../gfx/define'; import { Camera } from '../../../renderer/scene/camera'; import { Node } from '../../../scene-graph/node'; -import { Color, Rect, Size } from '../../../core/value-types'; +import { Color, Rect, Size, Vec3 } from '../../../core/value-types'; + +let _tempPos= new Vec3(); +let _worldPos = new Vec3(); /** * !#zh: 作为 UI 根节点,为所有子节点提供视窗四边的位置信息以供对齐,另外提供屏幕适配策略接口,方便从编辑器设置。 @@ -108,6 +111,7 @@ export class CanvasComponent extends Component { return this._camera; } + public static instance: CanvasComponent | null = null; public static views = []; /** * !#en The desigin resolution for current scene. @@ -139,6 +143,9 @@ export class CanvasComponent extends Component { constructor () { super(); this._thisOnResized = this.alignWithScreen.bind(this); + if(!CanvasComponent.instance){ + CanvasComponent.instance = this; + } } // public onLoad () {} @@ -167,6 +174,9 @@ export class CanvasComponent extends Component { isUI: true, }); + const device = cc.director.root.device; + this._camera.resize(device.width, device.height); + cc.director.root.ui.addScreen(this); // if (CC_DEV) { @@ -182,16 +192,18 @@ export class CanvasComponent extends Component { if (CC_EDITOR) { cc.director.on(cc.Director.EVENT_AFTER_UPDATE, this.alignWithScreen, this); - cc.engine.on('design-resolution-changed', this._thisOnResized); + // cc.view.on('canvas-resize', this._thisOnResized); + // cc.engine.on('design-resolution-changed', this._thisOnResized); } else { - if (cc.sys.isMobile) { - window.addEventListener('resize', this._thisOnResized); - } - else { - cc.view.on('canvas-resize', this._thisOnResized); - } + // if (cc.sys.isMobile) { + // window.addEventListener('resize', this._thisOnResized); + // } + // else { + // cc.view.on('canvas-resize', this._thisOnResized); + // } } + cc.view.on('canvas-size-update', this._thisOnResized); this.applySettings(); this.alignWithScreen(); @@ -207,24 +219,23 @@ export class CanvasComponent extends Component { public onDestroy () { if (CC_EDITOR) { cc.director.off(cc.Director.EVENT_AFTER_UPDATE, this.alignWithScreen, this); - cc.engine.off('design-resolution-changed', this._thisOnResized); + // cc.view.off('canvas-resize', this._thisOnResized); + // cc.engine.off('design-resolution-changed', this._thisOnResized); } - else { - if (cc.sys.isMobile) { - window.removeEventListener('resize', this._thisOnResized); - } else { - cc.view.off('canvas-resize', this._thisOnResized); - } - } - - cc.view.off('design-resolution-changed', this._thisOnResized); - - // if (CanvasComponent.instance === this) { - // CanvasComponent.instance = null; + // else { + // if (cc.sys.isMobile) { + // window.removeEventListener('resize', this._thisOnResized); + // } else { + // cc.view.off('canvas-resize', this._thisOnResized); + // } // } - } + cc.view.off('canvas-size-update', this._thisOnResized); + // cc.view.off('design-resolution-changed', this._thisOnResized); - // + if (CanvasComponent.instance === this) { + CanvasComponent.instance = null; + } + } public alignWithScreen() { let nodeSize, designSize; @@ -248,18 +259,20 @@ export class CanvasComponent extends Component { this.node.setPosition(canvasSize.width * 0.5 + offsetX, canvasSize.height * 0.5 + offsetY, 1); } - if(this.node.width!==nodeSize.width){ + if (this.node.width !== nodeSize.width) { this.node.width = nodeSize.width; } - if(this.node.height !== nodeSize.height){ + if (this.node.height !== nodeSize.height) { this.node.height = nodeSize.height; } - let nodeWorldPos = this.node.getWorldPosition(); + this.node.getWorldPosition(_worldPos); if (this._camera) { + const size = cc.view.getVisibleSize(); + this._camera.resize(size.width, size.height); this._camera.orthoHeight = this._camera.height / 2; - this._camera.node.setPosition(nodeWorldPos.x, nodeWorldPos.y, this._camera.node.getWorldPosition().z); + this._camera.node.setPosition(_worldPos.x, _worldPos.y, 1000); this._camera.update(); } } diff --git a/cocos/3d/ui/components/editbox/edit-box-impl.ts b/cocos/3d/ui/components/editbox/edit-box-impl.ts index 59b06fb3a4..a7dfbdbfb3 100644 --- a/cocos/3d/ui/components/editbox/edit-box-impl.ts +++ b/cocos/3d/ui/components/editbox/edit-box-impl.ts @@ -29,7 +29,7 @@ import { ccclass } from '../../../../core/data/class-decorator'; import macro from '../../../../core/platform/CCMacro'; import { contains } from '../../../../core/utils/misc'; -import { Color, Size } from '../../../../core/value-types'; +import { Color, Size, Mat4, Vec3 } from '../../../../core/value-types'; import * as math from '../../../../core/vmath'; import { Node } from '../../../../scene-graph/node'; import { UIRenderComponent } from '../ui-render-component'; @@ -47,9 +47,9 @@ const DELAY_TIME = 400; const FOCUS_DELAY_UC = 400; const FOCUS_DELAY_FIREFOX = 0; -const _matrix = cc.mat4(); -const _matrix_temp = cc.mat4(); -const _vec3 = cc.v3(); +const _matrix = new Mat4(); +const _matrix_temp = new Mat4(); +const _vec3 = new Vec3(); let _currentEditBoxImpl: EditBoxImpl | null = null; @@ -405,8 +405,7 @@ export class EditBoxImpl { node!.getWorldMatrix(_matrix); const transform = node!.uiTransfromComp; if (transform) { - _vec3.x = -transform.anchorX.x * transform.width; - _vec3.y = -transform.anchorY.y * transform.height; + math.vec3.set(_vec3, -transform.anchorX * transform.width, -transform.anchorY * transform.height, _vec3.z); } math.mat4.translate(_matrix, _matrix, _vec3); diff --git a/cocos/3d/ui/components/layout-component.ts b/cocos/3d/ui/components/layout-component.ts index 8136f00ef3..52e8f6d1b8 100644 --- a/cocos/3d/ui/components/layout-component.ts +++ b/cocos/3d/ui/components/layout-component.ts @@ -30,6 +30,7 @@ import { Size, Vec3, Rect, Vec2 } from '../../../core/value-types'; import { ccenum } from '../../../core/value-types/enum'; import { Node } from '../../../scene-graph/node'; import { UITransformComponent } from './ui-transfrom-component'; +import { vec3 } from '../../../core/vmath'; const NodeEvent = Node.EventType; /** * !#en Enum for Layout type @@ -890,12 +891,15 @@ export class LayoutComponent extends Component { return; } - let leftBottomInParentSpace = parentTransform.convertToNodeSpaceAR(cc.v2(allChildrenBoundingBox.x, allChildrenBoundingBox.y)); - leftBottomInParentSpace = cc.v2(leftBottomInParentSpace.x - this._paddingLeft, leftBottomInParentSpace.y - this._paddingBottom); + vec3.set(_tempPos, allChildrenBoundingBox.x, allChildrenBoundingBox.y, 0); + let leftBottomInParentSpace = new Vec3(); + parentTransform.convertToNodeSpaceAR(leftBottomInParentSpace, _tempPos); + vec3.set(leftBottomInParentSpace, leftBottomInParentSpace.x - this._paddingLeft, leftBottomInParentSpace.y - this._paddingBottom, leftBottomInParentSpace.z); - let rightTopInParentSpace = parentTransform.convertToNodeSpaceAR(cc.v2(allChildrenBoundingBox.x + allChildrenBoundingBox.width, - allChildrenBoundingBox.y + allChildrenBoundingBox.height)); - rightTopInParentSpace = cc.v2(rightTopInParentSpace.x + this._paddingRight, rightTopInParentSpace.y + this._paddingTop); + vec3.set(_tempPos, allChildrenBoundingBox.x + allChildrenBoundingBox.width, allChildrenBoundingBox.y + allChildrenBoundingBox.height, 0); + let rightTopInParentSpace = new Vec3(); + parentTransform.convertToNodeSpaceAR(rightTopInParentSpace, _tempPos); + vec3.set(rightTopInParentSpace, rightTopInParentSpace.x + this._paddingRight, rightTopInParentSpace.y + this._paddingTop, rightTopInParentSpace.z) const newSize = cc.size(parseFloat((rightTopInParentSpace.x - leftBottomInParentSpace.x).toFixed(2)), parseFloat((rightTopInParentSpace.y - leftBottomInParentSpace.y).toFixed(2))); @@ -925,8 +929,10 @@ export class LayoutComponent extends Component { paddingY = this._paddingTop; } + const self = this; + const fnPositionY = function (child, topOffset, row) { - return bottomBoundaryOfLayout + sign * (topOffset + child.anchorY * child.height * this._getUsedScaleValue(child.scaleY) + paddingY + row * this._spacingY); + return bottomBoundaryOfLayout + sign * (topOffset + child.anchorY * child.height * self._getUsedScaleValue(child.scaleY) + paddingY + row * this._spacingY); }.bind(this); let newHeight = 0; @@ -965,8 +971,9 @@ export class LayoutComponent extends Component { paddingX = this._paddingRight; } + const self = this; const fnPositionX = function (child, leftOffset, column) { - return leftBoundaryOfLayout + sign * (leftOffset + child.anchorX * child.width * this._getUsedScaleValue(child.scaleX) + paddingX + column * this._spacingX); + return leftBoundaryOfLayout + sign * (leftOffset + child.anchorX * child.width * self._getUsedScaleValue(child.scaleX) + paddingX + column * this._spacingX); }.bind(this); let newWidth = 0; diff --git a/cocos/3d/ui/components/scroll-bar-component.ts b/cocos/3d/ui/components/scroll-bar-component.ts index 5eb190143a..c5b2a15380 100644 --- a/cocos/3d/ui/components/scroll-bar-component.ts +++ b/cocos/3d/ui/components/scroll-bar-component.ts @@ -26,33 +26,37 @@ import { Component } from '../../../components/component'; import { clamp01 } from '../../../core/utils/misc'; -import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; -import { UIRenderComponent } from './ui-render-component'; -import { Vec3 } from '../../../core/value-types'; +import { ccclass, executionOrder, menu, property } from '../../../core/data/class-decorator'; +import { Vec3, Vec2, Size } from '../../../core/value-types'; import { Node } from '../../../scene-graph/node'; import { ScrollViewComponent } from './scroll-view-component'; -import { UITransformComponent } from './ui-transfrom-component'; import { vec3 } from '../../../core/vmath'; +import { SpriteComponent } from './sprite-component'; +import { ccenum } from '../../../core/value-types/enum'; const GETTINGSHORTERFACTOR = 20; const ZERO = new Vec3(); -const _tempPos = new Vec3(); +const _tempPos_1 = new Vec3(); +const _tempPos_2 = new Vec3(); +const defaultAnchor = new Vec2(); /** * Enum for Scrollbar direction * @enum Scrollbar.Direction */ -var Direction = cc.Enum({ +enum Direction { /** * @property {Number} HORIZONTAL */ - HORIZONTAL: 0, + HORIZONTAL = 0, /** * @property {Number} VERTICAL */ - VERTICAL: 1 -}); + VERTICAL = 1 +}; + +ccenum(Direction); /** * !#en @@ -63,12 +67,12 @@ var Direction = cc.Enum({ */ @ccclass('cc.ScrollBarComponent') @executionOrder(100) -@executeInEditMode +@menu('UI/ScrollBar') export class ScrollBarComponent extends Component { @property private _scrollView: ScrollViewComponent | null = null; @property - private _handle: UIRenderComponent | null = null; + private _handle: SpriteComponent | null = null; @property private _direction = Direction.HORIZONTAL; @property @@ -77,7 +81,7 @@ export class ScrollBarComponent extends Component { private _autoHideTime = 1.0; private _touching = false; - private _opacity = 0; + private _opacity = 255; private _autoHideRemainingTime = 0; /** @@ -86,13 +90,13 @@ export class ScrollBarComponent extends Component { * @property {Sprite} handle */ @property({ - type: UIRenderComponent + type: SpriteComponent }) get handle() { return this._handle; } - set handle(value: UIRenderComponent | null) { + set handle(value: SpriteComponent | null) { if (this._handle === value) { return } @@ -118,7 +122,7 @@ export class ScrollBarComponent extends Component { } this._direction = value; - this.onScroll(cc.v2(0, 0)); + this.onScroll(new Vec3()); } /** @@ -126,6 +130,7 @@ export class ScrollBarComponent extends Component { * !#zh 是否在没有滚动动作时自动隐藏 ScrollBar。 * @property {Boolean} enableAutoHide */ + @property get enableAutoHide() { return this._enableAutoHide; } @@ -166,7 +171,7 @@ export class ScrollBarComponent extends Component { static Direction = Direction; protected onEnable() { - let renderComp = this.node.getComponent(UIRenderComponent); + let renderComp = this.node.getComponent(SpriteComponent); if (renderComp) { this._opacity = renderComp.color.a; } @@ -197,28 +202,26 @@ export class ScrollBarComponent extends Component { return ZERO; } - const uiTransform = this._scrollView.node.getComponent(UITransformComponent)!; - const worldSpacePos = content.getWorldPosition(); - // const scrollViewSpacePos = uiTransform.convertToNodeSpace(worldSpacePos); - const scrollViewSpacePos = uiTransform.convertToNodeSpaceAR(worldSpacePos); + const worldSpacePos = content.uiTransfromComp!.convertToWorldSpace(ZERO); + const scrollViewSpacePos = this._scrollView.node.uiTransfromComp!.convertToNodeSpace(worldSpacePos); return scrollViewSpacePos; } private _setOpacity(opacity: number) { if (this._handle) { - let renderComp = this.node.getComponent(UIRenderComponent); + let renderComp = this.node.getComponent(SpriteComponent); if (renderComp) { renderComp.color.a = opacity; } - renderComp = this._handle.getComponent(UIRenderComponent); + renderComp = this._handle.getComponent(SpriteComponent); if (renderComp) { renderComp.color.a = opacity; } } } - public onScroll(outOfBoundary) { + public onScroll(outOfBoundary: Vec3) { if (!this._scrollView) { return } @@ -238,7 +241,7 @@ export class ScrollBarComponent extends Component { if (this._enableAutoHide) { this._autoHideRemainingTime = this._autoHideTime; - // this._setOpacity(this._opacity); + this._setOpacity(this._opacity); } let contentMeasure = 0; @@ -276,7 +279,7 @@ export class ScrollBarComponent extends Component { this._scrollView = scrollView; } - private _updateHanlderPosition(position) { + private _updateHanlderPosition(position: Vec3) { if (this._handle) { const oldPosition = this._fixupHandlerPosition(); @@ -285,30 +288,25 @@ export class ScrollBarComponent extends Component { } private _fixupHandlerPosition() { - if (!this._handle) { - return ZERO; - } - const barSize = this.node.getContentSize(); const barAnchor = this.node.getAnchorPoint(); - const handleSize = this._handle.node.getContentSize(); - // const handleParent = this._handle.node.parent!; - const handleTransform = handleParent.getComponent(UITransformComponent); - if (!handleTransform) { - return ZERO; + const handleSize = this.handle!.node.getContentSize(); + + const handleParent = this.handle!.node.parent!; + + + vec3.set(_tempPos_1, -barSize.width * barAnchor.x, -barSize.height * barAnchor.y, 0); + const leftBottomWorldPosition = this.node!.uiTransfromComp!.convertToWorldSpaceAR(_tempPos_2, _tempPos_1); + let fixupPosition = new Vec3(); + handleParent.uiTransfromComp!.convertToNodeSpaceAR(fixupPosition, leftBottomWorldPosition); + + if (this.direction === Direction.HORIZONTAL) { + fixupPosition = new Vec3(fixupPosition.x, fixupPosition.y + (barSize.height - handleSize.height) / 2, 0); + } else if (this.direction === Direction.VERTICAL) { + fixupPosition = new Vec3(fixupPosition.x + (barSize.width - handleSize.width) / 2, fixupPosition.y, 0); } - vec3.set(_tempPos, -barSize.width * barAnchor.x, -barSize.height * barAnchor.y) - const leftBottomWorldPosition = this.node.getWorldPosition(_tempPos); - const fixupPosition = handleParent.convertToNodeSpaceAR(leftBottomWorldPosition); - - if (this._direction === Direction.HORIZONTAL) { - fixupPosition = cc.v2(fixupPosition.x, fixupPosition.y + (barSize.height - handleSize.height) / 2); - } else if (this._direction === Direction.VERTICAL) { - fixupPosition = cc.v2(fixupPosition.x + (barSize.width - handleSize.width) / 2, fixupPosition.y); - } - - this._handle.node.setPosition(fixupPosition); + this.handle!.node.setPosition(fixupPosition); return fixupPosition; } @@ -320,7 +318,7 @@ export class ScrollBarComponent extends Component { this._touching = true; } - private _conditionalDisableScrollBar(contentSize, scrollViewSize) { + private _conditionalDisableScrollBar(contentSize: Size, scrollViewSize: Size) { if (contentSize.width <= scrollViewSize.width && this._direction === Direction.HORIZONTAL) { return true; } @@ -344,10 +342,10 @@ export class ScrollBarComponent extends Component { if (this._scrollView) { - var content = this._scrollView.content; + const content = this._scrollView.content; if (content) { - var contentSize = content.getContentSize(); - var scrollViewSize = this._scrollView.node.getContentSize(); + const contentSize = content.getContentSize(); + const scrollViewSize = this._scrollView.node.getContentSize(); if (this._conditionalDisableScrollBar(contentSize, scrollViewSize)) { return; @@ -358,41 +356,45 @@ export class ScrollBarComponent extends Component { this._autoHideRemainingTime = this._autoHideTime; } - private _calculateLength(contentMeasure, scrollViewMeasure, handleNodeMeasure, outOfBoundary) { - var denominatorValue = contentMeasure; + private _calculateLength(contentMeasure: number, scrollViewMeasure: number, handleNodeMeasure: number, outOfBoundary: number) { + let denominatorValue = contentMeasure; if (outOfBoundary) { denominatorValue += (outOfBoundary > 0 ? outOfBoundary : -outOfBoundary) * GETTINGSHORTERFACTOR; } - var lengthRation = scrollViewMeasure / denominatorValue; + const lengthRation = scrollViewMeasure / denominatorValue; return handleNodeMeasure * lengthRation; } - private _calculatePosition(contentMeasure, scrollViewMeasure, handleNodeMeasure, contentPosition, outOfBoundary, actualLenth) { - var denominatorValue = contentMeasure - scrollViewMeasure; + private _calculatePosition(contentMeasure: number, scrollViewMeasure: number, handleNodeMeasure: number, contentPosition: number, outOfBoundary: number, actualLenth: number) { + let denominatorValue = contentMeasure - scrollViewMeasure; if (outOfBoundary) { denominatorValue += Math.abs(outOfBoundary); } - var positionRatio = 0; + let positionRatio = 0; if (denominatorValue) { positionRatio = contentPosition / denominatorValue; positionRatio = clamp01(positionRatio); } - var position = (handleNodeMeasure - actualLenth) * positionRatio; + const position = (handleNodeMeasure - actualLenth) * positionRatio; if (this._direction === Direction.VERTICAL) { - return cc.v2(0, position); + return new Vec3(0, position, 0); } else { - return cc.v2(position, 0); + return new Vec3(position, 0, 0); } } - private _updateLength(length) { + private _updateLength(length: number) { if (this._handle) { - var handleNode = this._handle.node; - var handleNodeSize = handleNode.getContentSize(); - handleNode.setAnchorPoint(cc.v2(0, 0)); + let handleNode = this._handle.node; + const handleNodeSize = handleNode.getContentSize(); + const anchor = handleNode.getAnchorPoint(); + if(anchor.x !== defaultAnchor.x || anchor.y !== defaultAnchor.y){ + handleNode.setAnchorPoint(defaultAnchor); + } + if (this._direction === Direction.HORIZONTAL) { handleNode.setContentSize(length, handleNodeSize.height); } else { @@ -401,7 +403,7 @@ export class ScrollBarComponent extends Component { } } - private _processAutoHide(deltaTime) { + private _processAutoHide(deltaTime: number) { if (!this._enableAutoHide || this._autoHideRemainingTime <= 0) { return; } else if (this._touching) { @@ -412,8 +414,8 @@ export class ScrollBarComponent extends Component { this._autoHideRemainingTime -= deltaTime; if (this._autoHideRemainingTime <= this._autoHideTime) { this._autoHideRemainingTime = Math.max(0, this._autoHideRemainingTime); - // var opacity = this._opacity * (this._autoHideRemainingTime / this._autoHideTime); - // this._setOpacity(opacity); + const opacity = this._opacity * (this._autoHideRemainingTime / this._autoHideTime); + this._setOpacity(opacity); } } } diff --git a/cocos/3d/ui/components/scroll-view-component.ts b/cocos/3d/ui/components/scroll-view-component.ts index fdddf711e7..34e3b6bede 100644 --- a/cocos/3d/ui/components/scroll-view-component.ts +++ b/cocos/3d/ui/components/scroll-view-component.ts @@ -26,10 +26,13 @@ import { Node } from '../../../scene-graph/node'; import { Enum, Vec2, Vec3, Size } from '../../../core/value-types'; import { ViewGroupComponent } from './view-group-component'; -import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; +import { ccclass, executionOrder, menu, property } from '../../../core/data/class-decorator'; import { ScrollBarComponent } from './scroll-bar-component'; import ComponentEventHandler from '../../../components/CCComponentEventHandler'; import { LayoutComponent } from './layout-component'; +import { EventTouch } from '../../../core/platform/event-manager'; +import Touch from '../../../core/platform/event-manager/CCTouch'; +import { vec3 } from '../../../core/vmath'; const NodeEvent = Node.EventType; @@ -37,7 +40,8 @@ const NUMBER_OF_GATHERED_TOUCHES_FOR_MOVE_SPEED = 5; const OUT_OF_BOUNDARY_BREAKING_FACTOR = 0.05; const EPSILON = 1e-4; const MOVEMENT_FACTOR = 0.7; -const _vec3Zero = new Vec3(); +const ZERO = new Vec3(); +const _tempPos = new Vec3(); let quintEaseOut = function (time) { time -= 1; @@ -167,7 +171,6 @@ const eventMap = { @ccclass('cc.ScrollViewComponent') @executionOrder(100) @menu('UI/ScrollView') -@executeInEditMode export class ScrollViewComponent extends ViewGroupComponent { /** * !#en Enable horizontal scroll. @@ -219,7 +222,7 @@ export class ScrollViewComponent extends ViewGroupComponent { * @property {Number} bounceDuration */ @property({ - range: [1, 10] + range: [0, 10] }) public bounceDuration = 1; @@ -259,15 +262,15 @@ export class ScrollViewComponent extends ViewGroupComponent { private _autoScrolling = false; private _autoScrollAttenuate = false; - private _autoScrollStartPosition = new Vec3(0, 0); - private _autoScrollTargetDelta = new Vec3(0, 0); + private _autoScrollStartPosition = new Vec3(); + private _autoScrollTargetDelta = new Vec3(); private _autoScrollTotalTime = 0; private _autoScrollAccumulatedTime = 0; private _autoScrollCurrentlyOutOfBoundary = false; private _autoScrollBraking = false; - private _autoScrollBrakingStartPosition = new Vec3(0, 0); + private _autoScrollBrakingStartPosition = new Vec3(); - private _outOfBoundaryAmount = new Vec3(0, 0); + private _outOfBoundaryAmount = new Vec3(); private _outOfBoundaryAmountDirty = true; private _stopMouseWheel = false; private _mouseWheelEventElapsedTime = 0.0; @@ -277,6 +280,7 @@ export class ScrollViewComponent extends ViewGroupComponent { private _isBouncing = false; private _scrolling = false; private _contentPos = new Vec3(); + private _deltaPos = new Vec3(); /** * !#en This is a reference to the UI element to be scrolled. @@ -289,7 +293,7 @@ export class ScrollViewComponent extends ViewGroupComponent { get content() { return this._content; } - set content(value: Node) { + set content(value: Node | null) { if(this._content === value){ return; } @@ -310,7 +314,7 @@ export class ScrollViewComponent extends ViewGroupComponent { return this._horizontalScrollBar; } - set horizontalScrollBar(value: ScrollBarComponent) { + set horizontalScrollBar(value: ScrollBarComponent | null) { if(this._horizontalScrollBar === value){ return; } @@ -319,7 +323,8 @@ export class ScrollViewComponent extends ViewGroupComponent { if (this._horizontalScrollBar) { this._horizontalScrollBar.setScrollView(this); - this._updateScrollBar(0); + // this._updateScrollBar(0); + this._updateScrollBar(ZERO); } } @@ -328,12 +333,14 @@ export class ScrollViewComponent extends ViewGroupComponent { * !#zh 垂直滚动的 ScrollBar。 * @property {Scrollbar} verticalScrollBar */ - @property + @property({ + type: ScrollBarComponent + }) get verticalScrollBar() { return this._verticalScrollBar; } - set verticalScrollBar(value: ScrollBarComponent) { + set verticalScrollBar(value: ScrollBarComponent | null) { if (this._verticalScrollBar === value) { return; } @@ -342,10 +349,18 @@ export class ScrollViewComponent extends ViewGroupComponent { if (this._verticalScrollBar) { this._verticalScrollBar.setScrollView(this); - this._updateScrollBar(0); + this._updateScrollBar(ZERO); } } + get view() { + if (!this._content) { + return null; + } + + return this._content.parent; + } + static EventType = EventType; /** @@ -593,7 +608,7 @@ export class ScrollViewComponent extends ViewGroupComponent { let topDelta = this._getContentTopBoundary() - this._topBoundary; let leftDeta = this._getContentLeftBoundary() - this._leftBoundary; - return new Vec2(leftDeta, topDelta); + return new Vec3(leftDeta, topDelta, 0); } /** @@ -610,7 +625,7 @@ export class ScrollViewComponent extends ViewGroupComponent { horizontalMaximizeOffset = horizontalMaximizeOffset >= 0 ? horizontalMaximizeOffset : 0; verticalMaximizeOffset = verticalMaximizeOffset >= 0 ? verticalMaximizeOffset : 0; - return new Vec2(horizontalMaximizeOffset, verticalMaximizeOffset); + return new Vec3(horizontalMaximizeOffset, verticalMaximizeOffset, 0); } /** @@ -725,7 +740,11 @@ export class ScrollViewComponent extends ViewGroupComponent { * @returns {Position} - The content's position in its parent space. */ getContentPosition() { - this._content!.getPosition(this._contentPos); + if(!this._content){ + return ZERO; + } + + this._content.getPosition(this._contentPos); return this._contentPos; } @@ -751,19 +770,19 @@ export class ScrollViewComponent extends ViewGroupComponent { //private methods _registerEvent() { - this.node.on(cc.Node.EventType.TOUCH_START, this._onTouchBegan, this, true); - this.node.on(cc.Node.EventType.TOUCH_MOVE, this._onTouchMoved, this, true); - this.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this, true); - this.node.on(cc.Node.EventType.TOUCH_CANCEL, this._onTouchCancelled, this, true); - this.node.on(cc.Node.EventType.MOUSE_WHEEL, this._onMouseWheel, this, true); + this.node.on(NodeEvent.TOUCH_START, this._onTouchBegan, this, true); + this.node.on(NodeEvent.TOUCH_MOVE, this._onTouchMoved, this, true); + this.node.on(NodeEvent.TOUCH_END, this._onTouchEnded, this, true); + this.node.on(NodeEvent.TOUCH_CANCEL, this._onTouchCancelled, this, true); + this.node.on(NodeEvent.MOUSE_WHEEL, this._onMouseWheel, this, true); } _unregisterEvent() { - this.node.off(cc.Node.EventType.TOUCH_START, this._onTouchBegan, this, true); - this.node.off(cc.Node.EventType.TOUCH_MOVE, this._onTouchMoved, this, true); - this.node.off(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this, true); - this.node.off(cc.Node.EventType.TOUCH_CANCEL, this._onTouchCancelled, this, true); - this.node.off(cc.Node.EventType.MOUSE_WHEEL, this._onMouseWheel, this, true); + this.node.off(NodeEvent.TOUCH_START, this._onTouchBegan, this, true); + this.node.off(NodeEvent.TOUCH_MOVE, this._onTouchMoved, this, true); + this.node.off(NodeEvent.TOUCH_END, this._onTouchEnded, this, true); + this.node.off(NodeEvent.TOUCH_CANCEL, this._onTouchCancelled, this, true); + this.node.off(NodeEvent.MOUSE_WHEEL, this._onMouseWheel, this, true); } _onMouseWheel(event, captureListeners) { @@ -776,10 +795,10 @@ export class ScrollViewComponent extends ViewGroupComponent { wheelPrecision = -7; } if (this.vertical) { - deltaMove = new Vec3(0, event.getScrollY() * wheelPrecision); + deltaMove = new Vec3(0, event.getScrollY() * wheelPrecision, 0); } else if (this.horizontal) { - deltaMove = new Vec3(event.getScrollY() * wheelPrecision, 0); + deltaMove = new Vec3(event.getScrollY() * wheelPrecision, 0, 0); } this._mouseWheelEventElapsedTime = 0; @@ -787,7 +806,7 @@ export class ScrollViewComponent extends ViewGroupComponent { if (!this._stopMouseWheel) { this._handlePressLogic(); - this.schedule(this._checkMouseWheel, 1.0 / 60); + this.schedule(this._checkMouseWheel, 1.0 / 60, NaN, 0); this._stopMouseWheel = true; } @@ -798,7 +817,7 @@ export class ScrollViewComponent extends ViewGroupComponent { let currentOutOfBoundary = this._getHowMuchOutOfBoundary(); let maxElapsedTime = 0.1; - if (!currentOutOfBoundary.fuzzyEquals(_vec3Zero, EPSILON)) { + if (!currentOutOfBoundary.fuzzyEquals(ZERO, EPSILON)) { this._processInertiaScroll(); this.unschedule(this._checkMouseWheel); this._stopMouseWheel = false; @@ -831,7 +850,7 @@ export class ScrollViewComponent extends ViewGroupComponent { let leftDeta = this._getContentLeftBoundary() - this._leftBoundary; leftDeta = -leftDeta; - let moveDelta = new Vec3(0, 0); + let moveDelta = new Vec3(); let totalScrollDelta = 0; if (applyToHorizontal) { totalScrollDelta = contentSize.width - scrollSize.width; @@ -851,7 +870,7 @@ export class ScrollViewComponent extends ViewGroupComponent { let bottomDeta = this._getContentBottomBoundary() - this._bottomBoundary; bottomDeta = -bottomDeta; - let moveDelta = new Vec3(0, 0); + let moveDelta = new Vec3(); let totalScrollDelta = 0; let leftDeta = this._getContentLeftBoundary() - this._leftBoundary; @@ -889,52 +908,45 @@ export class ScrollViewComponent extends ViewGroupComponent { } _calculateBoundary() { - if (this._content) { - return; + if (this.content) { + //refresh content size + let layout = this.content.getComponent(LayoutComponent); + if (layout && layout.enabledInHierarchy) { + layout.updateLayout(); + } + let viewSize = this.view!.getContentSize(); + + let anchorX = viewSize.width * this.view!.anchorX; + let anchorY = viewSize.height * this.view!.anchorY; + + this._leftBoundary = -anchorX; + this._bottomBoundary = -anchorY; + + this._rightBoundary = this._leftBoundary + viewSize.width; + this._topBoundary = this._bottomBoundary + viewSize.height; + + this._moveContentToTopLeft(viewSize); } - //refresh content size - let layout = this._content!.getComponent(LayoutComponent); - if (layout && layout.enabledInHierarchy) { - layout!.updateLayout(); - } - let viewSize = this._content!.parent!.getContentSize(); - let leftBottomPosition = this._convertToContentParentSpace(new Vec3(0, 0)); - this._leftBoundary = leftBottomPosition.x; - this._bottomBoundary = leftBottomPosition.y; - - let topRightPosition = this._convertToContentParentSpace(new Vec3(viewSize.width, viewSize.height)); - this._rightBoundary = topRightPosition.x; - this._topBoundary = topRightPosition.y; - - this._moveContentToTopLeft(viewSize); - - } - - _convertToContentParentSpace(position: Vec3) { - let contentParent = this._content!.parent; - // TODO: - let viewPositionInWorldSpace = contentParent.convertToWorldSpace(position); - return contentParent.convertToNodeSpaceAR(viewPositionInWorldSpace); } //this is for nested scrollview - _hasNestedViewGroup(event, captureListeners) { - if (event.eventPhase !== cc.Event.CAPTURING_PHASE) return; + _hasNestedViewGroup(event?: EventTouch, captureListeners?: any) { + if (!event || event.eventPhase !== cc.Event.CAPTURING_PHASE) return; if (captureListeners) { //captureListeners are arranged from child to parent for (let i = 0; i < captureListeners.length; ++i) { - let item = captureListeners[i]; + let item = captureListeners[i] as Node; if (this.node === item) { - if (event.target.getComponent(cc.ViewGroup)) { + if (event.target && (event.target as Node).getComponent(ViewGroupComponent)) { return true; } return false; } - if (item.getComponent(cc.ViewGroup)) { + if (item.getComponent(ViewGroupComponent)) { return true; } } @@ -943,18 +955,18 @@ export class ScrollViewComponent extends ViewGroupComponent { } //This is for Scrollview as children of a Button - _stopPropagationIfTargetIsMe(event) { - if (event.eventPhase === cc.Event.AT_TARGET && event.target === this.node) { + _stopPropagationIfTargetIsMe(event?: EventTouch) { + if (event && event.eventPhase === cc.Event.AT_TARGET && event.target === this.node) { event.propagationStopped = true; } } // touch event handler - _onTouchBegan(event, captureListeners) { + _onTouchBegan(event?: EventTouch, captureListeners?: any) { if (!this.enabledInHierarchy||!this._content) return; if (this._hasNestedViewGroup(event, captureListeners)) return; - let touch = event.touch; + // let touch = event.touch; if (this._content) { this._handlePressLogic(); } @@ -962,10 +974,14 @@ export class ScrollViewComponent extends ViewGroupComponent { this._stopPropagationIfTargetIsMe(event); } - _onTouchMoved(event, captureListeners) { + _onTouchMoved(event?: EventTouch, captureListeners?: any) { if (!this.enabledInHierarchy || !this._content) return; if (this._hasNestedViewGroup(event, captureListeners)) return; + if (!event || !event.touch){ + return; + } + let touch = event.touch; if (this._content) { this._handleMoveLogic(touch); @@ -980,19 +996,19 @@ export class ScrollViewComponent extends ViewGroupComponent { if (deltaMove.mag() > 7) { if (!this._touchMoved && event.target !== this.node) { // Simulate touch cancel for target node - let cancelEvent = new cc.Event.EventTouch(event.getTouches(), event.bubbles); - cancelEvent.type = cc.Node.EventType.TOUCH_CANCEL; + let cancelEvent = new EventTouch(event.getTouches(), event.bubbles); + cancelEvent.type = NodeEvent.TOUCH_CANCEL; cancelEvent.touch = event.touch; - cancelEvent.simulate = true; - event.target.dispatchEvent(cancelEvent); + // cancelEvent.simulate = true; + (event.target as Node)!.dispatchEvent(cancelEvent); this._touchMoved = true; } } this._stopPropagationIfTargetIsMe(event); } - _onTouchEnded(event, captureListeners) { - if (!this.enabledInHierarchy || !this._content) return; + _onTouchEnded(event?: EventTouch, captureListeners?: any) { + if (!this.enabledInHierarchy || !this._content || !event) return; if (this._hasNestedViewGroup(event, captureListeners)) return; this._dispatchEvent('touch-up'); @@ -1008,12 +1024,12 @@ export class ScrollViewComponent extends ViewGroupComponent { } } - _onTouchCancelled(event, captureListeners) { + _onTouchCancelled(event?: EventTouch, captureListeners?: any) { if (!this.enabledInHierarchy || !this._content) return; if (this._hasNestedViewGroup(event, captureListeners)) return; // Filte touch cancel event send from self - if (!event.simulate) { + if (event && !event['simulate']) { let touch = event.touch; if (this._content) { this._handleReleaseLogic(touch); @@ -1027,9 +1043,10 @@ export class ScrollViewComponent extends ViewGroupComponent { this._gatherTouchMove(deltaMove); } - _handleMoveLogic(touch) { - let deltaMove = touch.getDelta(); - this._processDeltaMove(deltaMove); + _handleMoveLogic(touch: Touch) { + const delta = touch.getDelta(); + vec3.set(this._deltaPos, delta.x, delta.y, 0); + this._processDeltaMove(this._deltaPos); } _scrollChildren(deltaMove: Vec3) { @@ -1145,7 +1162,7 @@ export class ScrollViewComponent extends ViewGroupComponent { let bounceBackAmount = this._getHowMuchOutOfBoundary(); bounceBackAmount = this._clampDelta(bounceBackAmount); - if (bounceBackAmount.fuzzyEquals(_vec3Zero, EPSILON)) { + if (bounceBackAmount.fuzzyEquals(_tempPos, EPSILON)) { return false; } @@ -1167,7 +1184,7 @@ export class ScrollViewComponent extends ViewGroupComponent { let bounceBackStarted = this._startBounceBackIfNeeded(); if (!bounceBackStarted && this.inertia) { let touchMoveVelocity = this._calculateTouchMoveVelocity(); - if (!touchMoveVelocity.fuzzyEquals(_vec3Zero, EPSILON) && this.brake < 1) { + if (!touchMoveVelocity.fuzzyEquals(_tempPos, EPSILON) && this.brake < 1) { this._startInertiaScroll(touchMoveVelocity); } } @@ -1177,7 +1194,8 @@ export class ScrollViewComponent extends ViewGroupComponent { _handleReleaseLogic(touch) { let delta = touch.getDelta(); - this._gatherTouchMove(delta); + vec3.set(this._deltaPos, delta.x, delta.y, 0); + this._gatherTouchMove(this._deltaPos); this._processInertiaScroll(); if (this._scrolling) { @@ -1190,7 +1208,7 @@ export class ScrollViewComponent extends ViewGroupComponent { _isOutOfBoundary() { let outOfBoundary = this._getHowMuchOutOfBoundary(); - return !outOfBoundary.fuzzyEquals(_vec3Zero, EPSILON); + return !outOfBoundary.fuzzyEquals(ZERO, EPSILON); } _isNecessaryAutoScrollBrake() { @@ -1245,7 +1263,7 @@ export class ScrollViewComponent extends ViewGroupComponent { } else { let moveDelta = newPosition.sub(this.getContentPosition()); let outOfBoundary = this._getHowMuchOutOfBoundary(moveDelta); - if (!outOfBoundary.fuzzyEquals(_vec3Zero, EPSILON)) { + if (!outOfBoundary.fuzzyEquals(ZERO, EPSILON)) { newPosition = newPosition.add(outOfBoundary); reachedEnd = true; } @@ -1261,6 +1279,7 @@ export class ScrollViewComponent extends ViewGroupComponent { if (!this._autoScrolling) { this._isBouncing = false; + this._scrolling = false; this._dispatchEvent('scroll-ended'); } } @@ -1282,7 +1301,6 @@ export class ScrollViewComponent extends ViewGroupComponent { _startAttenuatingAutoScroll(deltaMove: Vec3, initialVelocity: Vec3) { let time = this._calculateAutoScrollTimeByInitalSpeed(initialVelocity.mag()); - let targetDelta = deltaMove.normalize(); let contentSize = this._content!.getContentSize(); let scrollviewSize = this.node.getContentSize(); @@ -1293,7 +1311,7 @@ export class ScrollViewComponent extends ViewGroupComponent { let attenuatedFactorX = this._calculateAttenuatedFactor(totalMoveWidth); let attenuatedFactorY = this._calculateAttenuatedFactor(totalMoveHeight); - targetDelta = new Vec3(targetDelta.x * totalMoveWidth * (1 - this.brake) * attenuatedFactorX, targetDelta.y * totalMoveHeight * attenuatedFactorY * (1 - this.brake)); + targetDelta = new Vec3(targetDelta.x * totalMoveWidth * (1 - this.brake) * attenuatedFactorX, targetDelta.y * totalMoveHeight * attenuatedFactorY * (1 - this.brake), 0); let originalMoveLength = deltaMove.mag(); let factor = targetDelta.mag() / originalMoveLength; @@ -1320,21 +1338,21 @@ export class ScrollViewComponent extends ViewGroupComponent { return Math.sqrt(Math.sqrt(initalSpeed / 5)); } - _startAutoScroll(deltaMove, timeInSecond, attenuated) { + _startAutoScroll(deltaMove: Vec3, timeInSecond: number, attenuated: boolean = false) { let adjustedDeltaMove = this._flattenVectorByDirection(deltaMove); this._autoScrolling = true; this._autoScrollTargetDelta = adjustedDeltaMove; this._autoScrollAttenuate = attenuated; - this._autoScrollStartPosition = this.getContentPosition(); + vec3.copy(this._autoScrollStartPosition, this.getContentPosition()); this._autoScrollTotalTime = timeInSecond; this._autoScrollAccumulatedTime = 0; this._autoScrollBraking = false; this._isScrollEndedWithThresholdEventFired = false; - this._autoScrollBrakingStartPosition = new Vec3(0, 0); + this._autoScrollBrakingStartPosition = new Vec3(); let currentOutOfBoundary = this._getHowMuchOutOfBoundary(); - if (!currentOutOfBoundary.fuzzyEquals(_vec3Zero, EPSILON)) { + if (!currentOutOfBoundary.fuzzyEquals(ZERO, EPSILON)) { this._autoScrollCurrentlyOutOfBoundary = true; } } @@ -1346,16 +1364,16 @@ export class ScrollViewComponent extends ViewGroupComponent { }, totalTime); if (totalTime <= 0 || totalTime >= 0.5) { - return new Vec3(0, 0); + return new Vec3(); } - let totalMovement = new Vec3(0, 0); + let totalMovement = new Vec3(); totalMovement = this._touchMoveDisplacements.reduce(function (a, b) { return a.add(b); }, totalMovement); return new Vec3(totalMovement.x * (1 - this.brake) / totalTime, - totalMovement.y * (1 - this.brake) / totalTime); + totalMovement.y * (1 - this.brake) / totalTime, 0); } _flattenVectorByDirection(vector: Vec3) { @@ -1367,9 +1385,9 @@ export class ScrollViewComponent extends ViewGroupComponent { _moveContent(deltaMove: Vec3, canStartBounceBack?: boolean) { let adjustedMove = this._flattenVectorByDirection(deltaMove); - let newPosition = this.getContentPosition().add(adjustedMove); + this.getContentPosition().add(adjustedMove, _tempPos); - this.setContentPosition(newPosition); + this.setContentPosition(_tempPos); let outOfBoundary = this._getHowMuchOutOfBoundary(); this._updateScrollBar(outOfBoundary); @@ -1400,12 +1418,12 @@ export class ScrollViewComponent extends ViewGroupComponent { } _getHowMuchOutOfBoundary(addition?: Vec3) { - addition = addition || new Vec3(0, 0); - if (addition.fuzzyEquals(_vec3Zero, EPSILON) && !this._outOfBoundaryAmountDirty) { + addition = addition || new Vec3(); + if (addition.fuzzyEquals(ZERO, EPSILON) && !this._outOfBoundaryAmountDirty) { return this._outOfBoundaryAmount; } - let outOfBoundaryAmount = new Vec3(0, 0); + let outOfBoundaryAmount = new Vec3(); if (this._getContentLeftBoundary() + addition.x > this._leftBoundary) { outOfBoundaryAmount.x = this._leftBoundary - (this._getContentLeftBoundary() + addition.x); } else if (this._getContentRightBoundary() + addition.x < this._rightBoundary) { @@ -1418,17 +1436,16 @@ export class ScrollViewComponent extends ViewGroupComponent { outOfBoundaryAmount.y = this._bottomBoundary - (this._getContentBottomBoundary() + addition.y); } - if (addition.fuzzyEquals(_vec3Zero, EPSILON)) { + if (addition.fuzzyEquals(ZERO, EPSILON)) { this._outOfBoundaryAmount = outOfBoundaryAmount; this._outOfBoundaryAmountDirty = false; } outOfBoundaryAmount = this._clampDelta(outOfBoundaryAmount); - return outOfBoundaryAmount; } - _updateScrollBar(outOfBoundary) { + _updateScrollBar(outOfBoundary: Vec3) { if (this._horizontalScrollBar) { this._horizontalScrollBar.onScroll(outOfBoundary); } @@ -1486,11 +1503,12 @@ export class ScrollViewComponent extends ViewGroupComponent { this._outOfBoundaryAmountDirty = true; if (this._isOutOfBoundary()) { - let outOfBoundary = this._getHowMuchOutOfBoundary(new Vec3(0, 0)); + let outOfBoundary = this._getHowMuchOutOfBoundary(new Vec3()); let newPosition = this.getContentPosition().add(outOfBoundary); if (this._content) { this._content.setPosition(newPosition); - this._updateScrollBar(0); + // this._updateScrollBar(0); + this._updateScrollBar(ZERO); } } } @@ -1527,15 +1545,13 @@ export class ScrollViewComponent extends ViewGroupComponent { onDisable() { if (!CC_EDITOR) { this._unregisterEvent(); - this.node.off(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this); - this.node.off(NodeEvent.SCALE_CHANGED, this._calculateBoundary, this); - if (this._content) { - this._content.off(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this); - this._content.off(NodeEvent.SCALE_CHANGED, this._calculateBoundary, this); - if (this._content.parent) { - this._content.parent.off(NodeEvent.POSITION_CHANGED, this._calculateBoundary, this); - this._content.parent.off(NodeEvent.SCALE_CHANGED, this._calculateBoundary, this); - this._content.parent.off(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this); + if (this.content) { + this.content.off(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this); + this.content.off(NodeEvent.SCALE_PART, this._calculateBoundary, this); + if (this.view!) { + this.view!.off(NodeEvent.POSITION_PART, this._calculateBoundary, this); + this.view!.off(NodeEvent.SCALE_PART, this._calculateBoundary, this); + this.view!.off(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this); } } } @@ -1546,15 +1562,13 @@ export class ScrollViewComponent extends ViewGroupComponent { onEnable() { if (!CC_EDITOR) { this._registerEvent(); - this.node.on(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this); - this.node.on(NodeEvent.SCALE_CHANGED, this._calculateBoundary, this); - if (this._content) { - this._content.on(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this); - this._content.on(NodeEvent.SCALE_CHANGED, this._calculateBoundary, this); - if (this._content.parent) { - this._content.parent.on(NodeEvent.POSITION_CHANGED, this._calculateBoundary, this); - this._content.parent.on(NodeEvent.SCALE_CHANGED, this._calculateBoundary, this); - this._content.parent.on(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this); + if (this.content) { + this.content.on(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this); + this.content.on(NodeEvent.SCALE_PART, this._calculateBoundary, this); + if (this.view!) { + this.view!.on(NodeEvent.POSITION_PART, this._calculateBoundary, this); + this.view!.on(NodeEvent.SCALE_PART, this._calculateBoundary, this); + this.view!.on(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this); } } } diff --git a/cocos/3d/ui/components/slider-component.ts b/cocos/3d/ui/components/slider-component.ts index 593b0cd237..1dde53ed94 100644 --- a/cocos/3d/ui/components/slider-component.ts +++ b/cocos/3d/ui/components/slider-component.ts @@ -34,6 +34,7 @@ import { vec3 } from '../../../core/vmath'; import { EventType } from '../../../scene-graph/node-event-enum'; import { SpriteComponent } from './sprite-component'; +const _tempPos = new Vec3(); /** * !#en The Slider Direction * !#zh 滑动器方向 @@ -203,7 +204,7 @@ export class SliderComponent extends Component { this._touchHandle = true; const touhPos = event.touch!.getLocation(); vec3.set(this._touchPos, touhPos.x, touhPos.y, 0); - this._offset = this._handle.node.uiTransfromComp.convertToNodeSpaceAR(this._touchPos); + this._handle.node.uiTransfromComp.convertToNodeSpaceAR(this._offset, this._touchPos); event.propagationStopped = true; } @@ -261,7 +262,7 @@ export class SliderComponent extends Component { if (!this._handle) { return; } const touchPos = (touch as EventTouch).getLocation(); vec3.set(this._touchPos, touchPos.x, touchPos.y, 0); - const localTouchPos = this.node.uiTransfromComp!.convertToNodeSpaceAR(this._touchPos); + const localTouchPos = this.node.uiTransfromComp!.convertToNodeSpaceAR(_tempPos, this._touchPos); if (this.direction === Direction.Horizontal) { this.progress = clamp01(0.5 + (localTouchPos.x - this._offset.x) / this.node.width!); } else { diff --git a/cocos/3d/ui/components/ui-transfrom-component.ts b/cocos/3d/ui/components/ui-transfrom-component.ts index 0d84dd8be9..f9b2dec496 100644 --- a/cocos/3d/ui/components/ui-transfrom-component.ts +++ b/cocos/3d/ui/components/ui-transfrom-component.ts @@ -195,6 +195,7 @@ export class UITransformComponent extends Component { } public isHit (point: Vec2, listener?: EventListener) { + // console.log('click point ' + point.toString()); const w = this._contentSize.width; const h = this._contentSize.height; const cameraPt = _vec2a; @@ -209,30 +210,15 @@ export class UITransformComponent extends Component { return; } + // 将一个摄像机坐标系下的点转换到世界坐标系下 canvas.node.getWorldRT(_mat4_temp); - const m12 = _mat4_temp.m12; const m13 = _mat4_temp.m13; - const center = cc.visibleRect.center; - // let size = cc.view.getFrameSize(); - // let center = cc.v2(size.width / 2, size.height / 2); - // let center = cc.v2(cc.game._renderer._device._gl.canvas.width / 2, cc.game._renderer._device._gl.canvas.height / 2); _mat4_temp.m12 = center.x - (_mat4_temp.m00 * m12 + _mat4_temp.m04 * m13); _mat4_temp.m13 = center.y - (_mat4_temp.m01 * m12 + _mat4_temp.m05 * m13); - - // if (out !== _mat4_temp) { - // mat4.copy(out, _mat4_temp); - // } math.mat4.invert(_mat4_temp, _mat4_temp); math.vec2.transformMat4(cameraPt, point, _mat4_temp); - // let camera = cc.Camera.findCamera(this); - // if (camera) { - // camera.getCameraToWorldPoint(point, cameraPt); - // } - // else { - // cameraPt.set(point); - // } this.node.getWorldMatrix(_worldMatrix); math.mat4.invert(_mat4_temp, _worldMatrix); @@ -241,6 +227,8 @@ export class UITransformComponent extends Component { testPt.y += this._anchorPoint.y * h; if (testPt.x >= 0 && testPt.y >= 0 && testPt.x <= w && testPt.y <= h) { + // console.log('wpos '+this.node.getWorldPosition().toString()); + // console.log('click '+this.node.name); // if (listener && listener.mask) { // const mask = listener.mask; // const parent = this; @@ -260,6 +248,50 @@ export class UITransformComponent extends Component { } } + /** + * !#en Converts a Point to node (local) space coordinates then add the anchor point position. + * So the return position will be related to the left bottom corner of the node's bounding box. + * This equals to the API behavior of cocos2d-x, you probably want to use convertToNodeSpaceAR instead + * !#zh 将一个点转换到节点 (局部) 坐标系,并加上锚点的坐标。
+ * 也就是说返回的坐标是相对于节点包围盒左下角的坐标。
+ * 这个 API 的设计是为了和 cocos2d-x 中行为一致,更多情况下你可能需要使用 convertToNodeSpaceAR。 + * @method convertToNodeSpace + * @param {Vec3} worldPoint + * @return {Vec3} + * @example + * var newVec2 = node.convertToNodeSpace(cc.v3(100, 100)); + */ + convertToNodeSpace(worldPoint: Vec3) { + this.node.getWorldMatrix(_worldMatrix); + math.mat4.invert(_mat4_temp, _worldMatrix); + let out = new Vec3(); + math.vec3.transformMat4(out, worldPoint, _mat4_temp); + out.x += this._anchorPoint.x * this._contentSize.width; + out.y += this._anchorPoint.y * this._contentSize.height; + return out; + } + + /** + * !#en Converts a Point related to the left bottom corner of the node's bounding box to world space coordinates. + * This equals to the API behavior of cocos2d-x, you probably want to use convertToWorldSpaceAR instead + * !#zh 将一个相对于节点左下角的坐标位置转换到世界空间坐标系。 + * 这个 API 的设计是为了和 cocos2d-x 中行为一致,更多情况下你可能需要使用 convertToWorldSpaceAR + * @method convertToWorldSpace + * @param {Vec3} nodePoint + * @return {Vec3} + * @example + * var newVec3 = node.convertToWorldSpace(cc.v3(100, 100)); + */ + convertToWorldSpace(nodePoint: Vec3) { + this.node.getWorldMatrix(_worldMatrix); + let out = new Vec3( + nodePoint.x - this._anchorPoint.x * this._contentSize.width, + nodePoint.y - this._anchorPoint.y * this._contentSize.height, + 0 + ); + return math.vec3.transformMat4(out, out, _worldMatrix); + } + /** * !#en * Converts a Point to node (local) space coordinates in which the anchor point is the origin position. diff --git a/cocos/3d/ui/components/view-group-component.ts b/cocos/3d/ui/components/view-group-component.ts index 9317c26127..8b46d10a22 100644 --- a/cocos/3d/ui/components/view-group-component.ts +++ b/cocos/3d/ui/components/view-group-component.ts @@ -45,3 +45,5 @@ import { Component } from "../../../components/component"; export class ViewGroupComponent extends Component{ } + +cc.ViewGroupComponent = ViewGroupComponent; diff --git a/cocos/3d/ui/components/widget-component.ts b/cocos/3d/ui/components/widget-component.ts index 868a112f99..ee0d61bfe2 100644 --- a/cocos/3d/ui/components/widget-component.ts +++ b/cocos/3d/ui/components/widget-component.ts @@ -486,19 +486,29 @@ export class WidgetComponent extends Component { this._isAbsVerticalCenter = value; } - get alignFlags(){ - return this._alignFlags; - } - - public static AlignMode = AlignMode; /** * !#zh: 对齐开关,由 AlignFlags 组成 - * * @property _alignFlags * @type {Number} * @default 0 * @private */ + @property + get alignFlags() { + return this._alignFlags; + } + + set alignFlags(value) { + if (this._alignFlags === value) { + return; + } + + this._alignFlags = value; + } + + public static AlignMode = AlignMode; + + @property private _alignFlags = 0; private _wasAlignOnce = false; // @property @@ -562,7 +572,7 @@ export class WidgetComponent extends Component { // this.alignMode = this._wasAlignOnce ? AlignMode.ONCE : AlignMode.ALWAYS; // this._wasAlignOnce = false; // } - this._target = this.node.parent; + if(this._alignMode === AlignMode.ONCE){ this._wasAlignOnce = true; } diff --git a/cocos/3d/ui/components/widget-manager.ts b/cocos/3d/ui/components/widget-manager.ts index 6c654d981f..574e93f2f3 100644 --- a/cocos/3d/ui/components/widget-manager.ts +++ b/cocos/3d/ui/components/widget-manager.ts @@ -59,21 +59,21 @@ export function computeInverseTransForTarget (widgetNode: Node, target: Node, ou let scaleY = scale.y; let translateX = 0; let translateY = 0; - for (const node = widgetNode.parent; ;) { + for (let node = widgetNode.parent; ;) { if (!node) { // ERROR: widgetNode should be child of target - // out_inverseTranslate.x = out_inverseTranslate.y = 0; - // out_inverseScale.x = out_inverseScale.y = 1; + out_inverseTranslate.x = out_inverseTranslate.y = 0; + out_inverseScale.x = out_inverseScale.y = 1; return; } const pos = node.getPosition(); translateX += pos.x; translateY += pos.y; - // node = node.parent; // loop increment + node = node.parent; // loop increment if (node !== target) { - scale = node.getScale(); + scale = node!.getScale(); const sx = scale.x; const sy = scale.y; translateX *= sx; diff --git a/cocos/assets/CCSpriteFrame.ts b/cocos/assets/CCSpriteFrame.ts index 64a7087f70..fb4d1e434b 100644 --- a/cocos/assets/CCSpriteFrame.ts +++ b/cocos/assets/CCSpriteFrame.ts @@ -25,7 +25,7 @@ THE SOFTWARE. ****************************************************************************/ -import { ccclass, property } from '../core/data/class-decorator'; +import { ccclass } from '../core/data/class-decorator'; import EventTarget from '../core/event/event-target'; import { addon } from '../core/utils/js'; import Rect, { rect } from '../core/value-types/rect'; diff --git a/cocos/core/platform/CCView.js b/cocos/core/platform/CCView.js index b63807bef8..2361a9badb 100644 --- a/cocos/core/platform/CCView.js +++ b/cocos/core/platform/CCView.js @@ -558,6 +558,7 @@ class View extends EventTarget { const w = width * this._devicePixelRatio; const h = height * this._devicePixelRatio; cc.director.root.resize(w, h); + this.emit('canvas-size-update'); canvas.style.width = width + 'px'; canvas.style.height = height + 'px'; diff --git a/cocos/renderer/ui/ui.ts b/cocos/renderer/ui/ui.ts index cf47c49472..8e1e8e49e3 100644 --- a/cocos/renderer/ui/ui.ts +++ b/cocos/renderer/ui/ui.ts @@ -359,8 +359,10 @@ export class UI { cmdBuff.endRenderPass(); } - this._renderArea.width = camera.width ; - this._renderArea.height = camera.height ; + // this._renderArea.width = camera.width; + // this._renderArea.height = camera.height; + this._renderArea.width = this._root.device.width; + this._renderArea.height = this._root.device.height; // TODO: add screen adapter // update ubo