summaryrefslogtreecommitdiffhomepage
path: root/Assets/Scripts/MovingSphere.cs
diff options
context:
space:
mode:
authorrealtradam <[email protected]>2022-12-08 01:02:01 -0500
committerrealtradam <[email protected]>2022-12-08 01:02:01 -0500
commitdd9ee2fabc55b99543a9aff4a6c27263902370bb (patch)
tree388f7ba2ab3860a1006bbef500f5d873a0b03079 /Assets/Scripts/MovingSphere.cs
parent6c3569682f9ada8a5f36c073c9a481818f480571 (diff)
downloadMagnet-Run-3D-dd9ee2fabc55b99543a9aff4a6c27263902370bb.tar.gz
Magnet-Run-3D-dd9ee2fabc55b99543a9aff4a6c27263902370bb.zip
implement basic physics
Diffstat (limited to 'Assets/Scripts/MovingSphere.cs')
-rw-r--r--Assets/Scripts/MovingSphere.cs68
1 files changed, 68 insertions, 0 deletions
diff --git a/Assets/Scripts/MovingSphere.cs b/Assets/Scripts/MovingSphere.cs
new file mode 100644
index 0000000..1f492aa
--- /dev/null
+++ b/Assets/Scripts/MovingSphere.cs
@@ -0,0 +1,68 @@
+using System.Collections;
+using System.Collections.Generic;
+using UnityEngine;
+
+public class MovingSphere : MonoBehaviour
+{
+ [SerializeField, Range(1f, 100f)]
+ float maxSpeed = 10f;
+ [SerializeField, Range(1f, 100f)]
+ float maxAcceleration = 10f;
+
+ [SerializeField, Range(0f, 1f)]
+ float bounciness = 0.5f;
+
+ Rect allowedArea = new Rect(-4.5f, -4.5f, 9f, 9f);
+
+ Vector3 velocity;
+
+ // Start is called before the first frame update
+ void Start()
+ {
+
+ }
+
+ // Update is called once per frame
+ void Update()
+ {
+ Vector2 playerInput = new Vector2(
+ Input.GetAxis("Horizontal"),
+ Input.GetAxis("Vertical")
+ );
+ playerInput = Vector2.ClampMagnitude(playerInput, 1f);
+
+ Vector3 acceleration = new Vector3(
+ playerInput.x,
+ 0f,
+ playerInput.y
+ ) * maxAcceleration;
+ velocity += acceleration * Time.deltaTime;
+ velocity = Vector3.ClampMagnitude(velocity, maxSpeed);
+ Vector3 displacement = velocity * Time.deltaTime;
+
+ Vector3 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;
+ }
+
+ transform.localPosition = newPosition;
+ }
+}