Unity小球移动
摘自Catlike的Movement Tutorial
小球移动
创建小球
使用Input System包,在Package Manager中Unity包搜索即可
创建Input Action资产
创建小球,包含拖尾渲染器、Player Input组件、脚本SphereMovement.cs
移动脚本
public class SphereMovement : MonoBehaviour { [FormerlySerializedAs("movementSpeed")] [Header("Movement Setting")] [SerializeField, Range(0f, 10f)] private float maxSpeed = 5f; [SerializeField, Range(0f, 100f)] private float maxAcceleration = 10f; [SerializeField] Rect allowedArea = new Rect(-5f, -5f, 10f, 10f);
public Vector3 Velocity; private PlayerInput _input; private Vector2 _moveInput;
private void Start() { _input = GetComponent<PlayerInput>(); Velocity = Vector3.zero; }
private void Update() { _moveInput = _input.actions["Move"].ReadValue<Vector2>(); Vector3 desiredVelocity = new Vector3(_moveInput.x, 0, _moveInput.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); Vector3 displacement = Velocity * Time.deltaTime; Vector3 newPosition = transform.localPosition + displacement; if (newPosition.x < allowedArea.xMin) { newPosition.x = allowedArea.xMin; Velocity.x = 0f; } else if (newPosition.x > allowedArea.xMax) { newPosition.x = allowedArea.xMax; Velocity.x = 0f; } if (newPosition.z < allowedArea.yMin) { newPosition.z = allowedArea.yMin; Velocity.z = 0f; } else if (newPosition.z > allowedArea.yMax) { newPosition.z = allowedArea.yMax; Velocity.z = 0f; } transform.localPosition = newPosition; } }
|