How to programmatically scale a canvas element to always be touching another moving canvas element

Hey,

I need help with making an image scale so that its right end is always touching the left end of another moving element.

So I have a seatbelt composed of two images:

  • Tongue.
  • Belt.

68813-seatbelt.png

These are all images within a Canvas and they’re anchored to the left.

Basically what I want to happen is:

  1. The tongue moves on the X axis (by touching and dragging).
  2. The seatbelt stretches its scale on the X axis so its right end is always touching the tongue, and its left end is stationary.

I’ve tried to workout the logic for this and I narrowed it down to a few points:

  • Store initial position of target (tongue), and initial scale of belt.
  • Calculate how far target has moved from start position.
  • Set belt’s X scale to be initalScale.x + deltaTargetX multiplied by some factor (I haven’t been able to figure this out yet).

So far, The belt does move in the proper directions, but it’s way off (probably due to a missing variable in my scaling) by either too much or too little.

I haven’t figured out whether I should be using anchoredPositions from the RectTransforms, or just use positions from Transforms. I’ve done something similar in the past but not on a Canvas.

Here is a sample project (Apologies for the weird stuff going on in the script, I’m still lost on what to do).

i think the UGUI system can do this for you without you writing any code for the belt/tongue positioning.

make the “Tongue” object a child of the “Belt” object,
and set the Tongue’s X-anchors to be Min: 1 and Max: 1.

then stretch the size of the Belt object, and the Tongue moves relative to the right-hand edge of the Belt.