Hi, can someone tell me how can I scroll my scroller view to a specific button?
Scenario
- There are 150 level buttons in a scrollview
- My current level is 55
- I scroll up to level 101
- Now I want to press a single button which will scroll me down to the 55th level button
- Also some levels’ buttons can be larger than others, so equally dividing 0 to 1 values into all levels will not work.
Tried Solution
- Find the value of scroll for each level
- Then use that scrollbar value to recentre the level.
- But that does not seem like the most efficient solution :-/
The tried solution would be the way I would go about it.
Assuming all the level buttons are children of the scroll view and in the correct order, I would get level button entity and use the local Y position of the button to use for the scrollbar value.
1 Like
Actually been trying this myself and it’s trickier than I thought as the scroll distance is smaller than the actually content so my method doesn’t work 
Turns out it was simpler than I thought. Overthought it a bit:
Main bulk of the code:
// initialize code called once per entity
MoveToLevelButton.prototype.initialize = function() {
this._scroll = new pc.Vec2();
this.entity.button.on('click', function() {
var scrollView = this.scrollViewEntity.scrollview;
var contentEntity = this.scrollViewEntity.findByName('Content');
var viewportEntity = this.scrollViewEntity.findByName('Viewport');
// Find the level button (assume that they are all in order children)
var levelButtonEntity = contentEntity.children[this.levelNumber - 1];
if (levelButtonEntity) {
// Inverse the position to work with
var y = contentEntity.element.height - levelButtonEntity.getLocalPosition().y;
this._scroll.copy(scrollView.scroll);
this._scroll.y = pc.math.clamp(y / (contentEntity.element.height - viewportEntity.element.height), 0, 1);
scrollView.scroll = this._scroll;
}
}, this);
};
Project: https://playcanvas.com/editor/scene/1246830
Thanks, and yes it is. Though my situation is a bit different. I have few containers inside scroll view and those containers contain different numbers of levels in them.
I think I will have to get globalPosition and use it to scroll
Global position may not be suitable due to scaling of the UI.
You may have to take the level button transform/position and multiple up through the parents’ transform till you reach a child of the content entity.
1 Like
That’s right, the global position will not be suitable. I will have to get the position of parent container then adding child position and subtracting half of the container size will give exact position.