抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

Unity小球移动

摘自Catlike的Movement Tutorial

小球移动

创建小球

使用Input System包,在Package Manager中Unity包搜索即可

创建Input Action资产

inputAction

创建小球,包含拖尾渲染器、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;
// |target - current| <= maxDelta ? target : current + maxDelta
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;
}
}

小球移动1

评论