Rigidbody
This commit is contained in:
@ -7,14 +7,15 @@ public class MovingSphere : MonoBehaviour
|
||||
|
||||
[SerializeField, Range(0f, 100f)]
|
||||
private float maxAcceleration = 10f;
|
||||
|
||||
private Rigidbody body;
|
||||
|
||||
[SerializeField, Range(0f, 1f)]
|
||||
private float bounciness = 0.5f;
|
||||
private Vector3 desiredVelocity;
|
||||
|
||||
[SerializeField]
|
||||
private Rect allowedArea = new Rect(-5f, -5f, 10f, 10f);
|
||||
|
||||
private Vector3 velocity;
|
||||
private void Awake()
|
||||
{
|
||||
body = GetComponent<Rigidbody>();
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
@ -22,37 +23,15 @@ public class MovingSphere : MonoBehaviour
|
||||
playerInput.x = Input.GetAxis("Horizontal");
|
||||
playerInput.y = Input.GetAxis("Vertical");
|
||||
playerInput = Vector2.ClampMagnitude(playerInput, 1f);
|
||||
var desiredVelocity = new Vector3(playerInput.x, 0f, playerInput.y) * maxSpeed;
|
||||
desiredVelocity = new Vector3(playerInput.x, 0f, playerInput.y) * maxSpeed;
|
||||
}
|
||||
|
||||
private void FixedUpdate()
|
||||
{
|
||||
var velocity = body.velocity;
|
||||
float maxSpeedChange = maxAcceleration * Time.deltaTime;
|
||||
velocity.x = Mathf.MoveTowards(velocity.x, desiredVelocity.x, maxSpeedChange);
|
||||
velocity.z = Mathf.MoveTowards(velocity.z, desiredVelocity.z, maxSpeedChange);
|
||||
var displacement = velocity * Time.deltaTime;
|
||||
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;
|
||||
body.velocity = velocity;
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user