Controlling Velocity

This commit is contained in:
_Redstone_c_ 2021-02-01 18:26:46 +08:00
parent ea974fca0d
commit 59d464eac4
2 changed files with 15 additions and 1 deletions

View File

@ -626,3 +626,4 @@ MonoBehaviour:
m_Script: {fileID: 11500000, guid: 50beb4685c906ba49b7db3438cc30dfc, type: 3}
m_Name:
m_EditorClassIdentifier:
maxSpeed: 10

View File

@ -2,12 +2,25 @@
public class MovingSphere : MonoBehaviour
{
[SerializeField, Range(0f, 100f)]
private float maxSpeed = 10f;
[SerializeField, Range(0f, 100f)]
private float maxAcceleration = 10f;
private Vector3 velocity;
private void Update()
{
Vector2 playerInput;
playerInput.x = Input.GetAxis("Horizontal");
playerInput.y = Input.GetAxis("Vertical");
playerInput = Vector2.ClampMagnitude(playerInput, 1f);
transform.localPosition = new Vector3(playerInput.x, 0.5f, playerInput.y);
var desiredVelocity = new Vector3(playerInput.x, 0f, playerInput.y) * maxSpeed;
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;
transform.localPosition += displacement;
}
}