- Home /
Calculating normalized horizontal position based on container size with fixed item size
Hi,
I'm building a little list of items inside a ScrollRect and would like to jump to any of them giving an index.
Based on inspector my items are 56x56 and the container has a width of 932. As an example I have tried to jump to an item manually (5th item in this example) just by setting normalizedHorizontalPostion to (5*56)/932. But this seems not quite right. If I set the Content rect position to -5*56 it shows my item at correct position (in the inspector) but when i try to set this through the scrollrect normalized horizontal position I can see in the inspector that the container is not jumping to the expected position.
Is there anything I am missing? Must I have any other internal screen rect or container rect position variables into account for this?.
Cheers.
Answer by Scribe · Sep 09, 2015 at 09:51 AM
This is untested:
w = visible area of scrollrect
mW = 932; //total width of scroll rect
pos = (itemcount - 1)*56; //0 indexed, hence 1st item should read (1-1)*56 = 0
return ((Mathf.Clamp(pos+w/2f, w/2f, mW - w/2f)-w/2f)/(mW-w))
Maybe that will work, if the scroll bar interpolates linearly I believe it should!
Thanks for the answer but this is not what I'm looking for. The math I'm applying is correct. I have checked several times. The main problem is when i try to translate it to set the normalizedHorizontalPosition because I think I'm missing something related to RectTransform inner workings. A simple example like, I have 10 items evently positioned (56 units wide) under the content transform. Each item should be reached just by assigning (1/10)*item to the normalizedhorizontalPosition. But when I set normalizedHorizontalPosition to for example (1/10)*4 it is not at correct position. On the other hand I expect my container x position to be at -4*56 units but it is not either.
Cheers.
The maths you are applying is not correct, it assumes the view area can move a total of 932 pixels, but that implies that when you get to the end of the scroll view, you have scrolled beyond the edge.
Think about it. At position 0 you can see pixel 1 on the left, at position 1, you see pixel 932 on the RIGHT not the left. so you have not moved 932 pixels despite that being the width of the scroll rect.
I fell so ashamed now... How the hell I did miss that? Thanks for noticing the problem, I was so focuses that I did not see it. By the way how can I accept this at the correct answer?. It seems I can't because my reputation is too low?
No problem, it is a little confusing, especially when the other way feels so obviously correct! You should be able to accept it now, as I have converted it from a comment to an answer :)