Unity/C#中X轴范围限制函数简化方案咨询
简化方案
你的代码逻辑是通过调整水平移动方向,让角色保持在X轴-3到3的范围内,可通过以下方式简化:
方法1:精简函数逻辑
优化rangeBoundX函数的结构,同时调整变量名提升可读性:
// 调整水平移动方向,确保角色X轴处于指定区间内 float AdjustHorizontalDirection(float currentX, float upperBound, float lowerBound, float currentDirection) { return currentX > upperBound ? -1f : currentX < lowerBound ? 1f : currentDirection; }
同时简化FixedUpdate里的冗余变量操作:
private void FixedUpdate() { Vector3 enemyForwardMove = transform.forward * enemySpeed * Time.fixedDeltaTime; // 直接使用当前X轴位置判断,避免多余的Vector3赋值 magn = AdjustHorizontalDirection(transform.position.x, 3f, -3f, magn); Vector3 horizontalMove = transform.right * magn * freq; enemyRB.MovePosition(enemyRB.position + enemyForwardMove + horizontalMove); }
方法2:完全内联逻辑(更简洁)
如果该范围判断仅在此处使用,可直接将逻辑内联到FixedUpdate中,省去函数调用的冗余:
private void FixedUpdate() { Vector3 enemyForwardMove = transform.forward * enemySpeed * Time.fixedDeltaTime; // 直接内联方向调整逻辑 if (transform.position.x > 3f) magn = -1f; else if (transform.position.x < -3f) magn = 1f; // 未越界则保持原magn值 Vector3 horizontalMove = transform.right * magn * freq; enemyRB.MovePosition(enemyRB.position + enemyForwardMove + horizontalMove); }
额外优化建议
- 将X轴范围(-3到3)定义为常量,方便后续统一修改:
private const float XUpperBound = 3f; private const float XLowerBound = -3f; - 变量名遵循C#驼峰命名规范(如
enemyforwardMove改为enemyForwardMove),提升代码可读性
内容的提问来源于stack exchange,提问作者Owlhunter1
相关产品推荐
相关产品推荐

