This repository has been archived on 2024-11-16. You can view files and clone it, but cannot push or open issues or pull requests.

38 lines
1.0 KiB
C#
Raw Normal View History

2021-02-02 15:10:30 +08:00
using UnityEngine;
public class MovingSphere : MonoBehaviour
{
[SerializeField, Range(0f, 100f)]
private float maxSpeed = 10f;
[SerializeField, Range(0f, 100f)]
private float maxAcceleration = 10f;
2021-02-02 16:28:38 +08:00
private Rigidbody body;
2021-02-02 15:10:30 +08:00
2021-02-02 16:28:38 +08:00
private Vector3 desiredVelocity;
2021-02-02 15:10:30 +08:00
2021-02-02 16:28:38 +08:00
private void Awake()
{
body = GetComponent<Rigidbody>();
}
2021-02-02 15:10:30 +08:00
private void Update()
{
Vector2 playerInput;
playerInput.x = Input.GetAxis("Horizontal");
playerInput.y = Input.GetAxis("Vertical");
playerInput = Vector2.ClampMagnitude(playerInput, 1f);
2021-02-02 16:28:38 +08:00
desiredVelocity = new Vector3(playerInput.x, 0f, playerInput.y) * maxSpeed;
}
private void FixedUpdate()
{
var velocity = body.velocity;
2021-02-02 15:10:30 +08:00
float maxSpeedChange = maxAcceleration * Time.deltaTime;
velocity.x = Mathf.MoveTowards(velocity.x, desiredVelocity.x, maxSpeedChange);
velocity.z = Mathf.MoveTowards(velocity.z, desiredVelocity.z, maxSpeedChange);
2021-02-02 16:28:38 +08:00
body.velocity = velocity;
2021-02-02 15:10:30 +08:00
}
}