Я пытаюсь получить разницу в ширине между холстом и изображением, которое масштабируется на CanvasScaler
, чтобы создать перевод между изображением и его границей.
Иллюстрация: ![Illustration](https://i.stack.imgur.com/KhLTv.png)
Как получить размер красной стрелки?
[РЕДАКТИРОВАТЬ 1]
Фрагмент кода ниже дай мне возможный правильный результат
var dist = (canvasRectTransform.rect.width - image.sprite.rect.width) / 2;
Но, похоже, он неверный:
public class Background : Monobehaviour
{
private float dist;
private float _percentage;
private float _currentLerpTime;`
private readonly Dictionary<LerpDirection, Func<Vector3>> _lerpDirectionActions;
public float lerpTime;
void Awake()
{
var image = GetComponent<Image>();
var canvasRectTransform = GetComponentInParent<RectTransform>();
dist = (canvasRectTransform.rect.width - image.sprite.rect.width) / 2;
_lerpDirectionActions = new Dictionary<LerpDirection, Func<Vector3>>
{
[LerpDirection.Left] = LerpToLeft,
[LerpDirection.Right] = LerpToRight
};
}
private Vector3 Lerp()
{
return Vector3.Lerp(
transform.position,
_lerpDirectionActions[lerpDirection].Invoke(), // will call LerpToRight or LerpToLeft
_percentage
);
}
private float LerpX => Lerp().x;
private Vector3 LerpToRight()
{
return new Vector3(transform.position.x - dist, transform.position.y);
}
private Vector3 LerpToLeft()
{
return new Vector3(transform.position.x + dist , transform.position.y);
}
void Update()
{
_currentLerpTime += Time.deltaTime;
_percentage = _currentLerpTime / lerpTime;
var localPositionX = tranform.position.x;
var mustGoRight = localPositionX <= 0 && lerpDirection == LerpDirection.Right;
var mustGoLeft = localPositionX >= dist && lerpDirection == LerpDirection.Left;
if (mustGoLeft || mustGoRight)
{
direction = direction.Invert(); // invert direction
Reset();
}
tranform.position = new Vector3(LerpX, tranform.position.y)
}
}
Сценарий Background
применяется к Background GameObject.
_lerpDirectionActions[lerpDirection].Invoke()
этот код выше будет вызывать правую функцию для рыскания слева или справа.
Иллюстрация: ![issue](https://image.noelshack.com/fichiers/2020/07/4/1581604514-issue.gif)
Перевод меняет направление, но не тогда, когда холст находится на границе изображения.