From c7ad4d418fffa3c278871968afefb96a1663ed31 Mon Sep 17 00:00:00 2001 From: _Redstone_c_ Date: Mon, 1 Feb 2021 18:56:10 +0800 Subject: [PATCH] Constraining Position - Done! --- Assets/Scenes/SampleScene.unity | 8 ++++++++ Assets/Scripts/MovingSphere.cs | 34 ++++++++++++++++++++++++++++++++- 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/Assets/Scenes/SampleScene.unity b/Assets/Scenes/SampleScene.unity index ca5a89b..51a9fbc 100644 --- a/Assets/Scenes/SampleScene.unity +++ b/Assets/Scenes/SampleScene.unity @@ -627,3 +627,11 @@ MonoBehaviour: m_Name: m_EditorClassIdentifier: maxSpeed: 10 + maxAcceleration: 10 + bounciness: 0.5 + allowedArea: + serializedVersion: 2 + x: -4.5 + y: -4.5 + width: 9 + height: 9 diff --git a/Assets/Scripts/MovingSphere.cs b/Assets/Scripts/MovingSphere.cs index f105322..3d069dc 100644 --- a/Assets/Scripts/MovingSphere.cs +++ b/Assets/Scripts/MovingSphere.cs @@ -8,6 +8,12 @@ public class MovingSphere : MonoBehaviour [SerializeField, Range(0f, 100f)] private float maxAcceleration = 10f; + [SerializeField, Range(0f, 1f)] + private float bounciness = 0.5f; + + [SerializeField] + private Rect allowedArea = new Rect(-5f, -5f, 10f, 10f); + private Vector3 velocity; private void Update() @@ -21,6 +27,32 @@ public class MovingSphere : MonoBehaviour velocity.x = Mathf.MoveTowards(velocity.x, desiredVelocity.x, maxSpeedChange); velocity.z = Mathf.MoveTowards(velocity.z, desiredVelocity.z, maxSpeedChange); var displacement = velocity * Time.deltaTime; - transform.localPosition += displacement; + var newPosition = transform.localPosition + displacement; + if (newPosition.x < allowedArea.xMin) + { + newPosition.x = allowedArea.xMin; + velocity.x = -velocity.x * bounciness; + } + else if (newPosition.x > allowedArea.xMax) + { + newPosition.x = allowedArea.xMax; + velocity.x = -velocity.x * bounciness; + } + if (newPosition.z < allowedArea.yMin) + { + newPosition.z = allowedArea.yMin; + velocity.z = -velocity.z * bounciness; + } + else if (newPosition.z > allowedArea.yMax) + { + newPosition.z = allowedArea.yMax; + velocity.z = -velocity.z * bounciness; + } + if (!allowedArea.Contains(new Vector2(newPosition.x, newPosition.z))) + { + newPosition.x = Mathf.Clamp(newPosition.x, allowedArea.xMin, allowedArea.xMax); + newPosition.z = Mathf.Clamp(newPosition.z, allowedArea.yMin, allowedArea.yMax); + } + transform.localPosition = newPosition; } }