Created
May 9, 2025 17:54
-
-
Save Nattuhan/65cdc9182e78ef8d36fd7083a7000f1e to your computer and use it in GitHub Desktop.
[Unity] Parallax effect can be obtained by attaching to multiple Images
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using UnityEngine; | |
| /// <summary> | |
| /// RectTransformをマウスの位置に応じて動かすコンポーネントです | |
| /// 複数のImageなどにつけることで、Parallax的な効果を得られます | |
| /// </summary> | |
| [RequireComponent(typeof(RectTransform))] | |
| public class ParallaxUI : MonoBehaviour | |
| { | |
| [SerializeField] private float moveAmount = 10f; | |
| private RectTransform rectTransform; | |
| private Vector3 initialLocalPos; | |
| private void Start() | |
| { | |
| rectTransform = GetComponent<RectTransform>(); | |
| initialLocalPos = rectTransform.localPosition; | |
| } | |
| private void Update() | |
| { | |
| Vector2 mousePos = Input.mousePosition; | |
| var screenSize = new Vector2(Screen.width, Screen.height); | |
| var normalized = (mousePos - screenSize * 0.5f) / (screenSize * 0.5f); | |
| var offset = new Vector2(normalized.x * moveAmount, normalized.y * moveAmount); | |
| rectTransform.localPosition = initialLocalPos + (Vector3)offset; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment