You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Unity脚本中W/S键移动逻辑仅在对象y坐标处于-7~7区间时生效?

给Unity移动脚本添加Y轴边界限制

要实现仅在物体Y坐标处于-7到7之间时响应W/S键移动,只需在原脚本的移动逻辑前增加坐标范围判断即可,有两种常用修改方式:

方式一:全局范围判断(仅在区间内才处理所有移动输入)

这种方式下,只要物体Y坐标超出[-7,7],就完全不响应W/S键的任何输入:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Left : MonoBehaviour
{
    public float playerSpeed = 8;

    void Update()
    {
        // 仅当Y坐标在(-7,7)区间内时,才处理移动输入
        if (transform.position.y > -7 && transform.position.y < 7)
        {
            if (Input.GetKey(KeyCode.W))
            {
                transform.position += new Vector3(0, playerSpeed * Time.deltaTime, 0);
            }

            if (Input.GetKey(KeyCode.S))
            {
                transform.position += new Vector3(0, -playerSpeed * Time.deltaTime, 0);
            }
        }
    }
}

方式二:分方向单独判断(允许边界处往回移动)

这种方式更实用:当物体Y坐标达到7时,禁止向上移动但允许向下;达到-7时禁止向下但允许向上:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Left : MonoBehaviour
{
    public float playerSpeed = 8;

    void Update()
    {
        // Y坐标小于7时,才允许向上移动
        if (Input.GetKey(KeyCode.W) && transform.position.y < 7)
        {
            transform.position += new Vector3(0, playerSpeed * Time.deltaTime, 0);
        }

        // Y坐标大于-7时,才允许向下移动
        if (Input.GetKey(KeyCode.S) && transform.position.y > -7)
        {
            transform.position += new Vector3(0, -playerSpeed * Time.deltaTime, 0);
        }
    }
}

核心修改说明

两种方式都是通过判断transform.position.y的数值范围,限制移动逻辑的执行时机,确保物体不会超出指定的Y轴边界。

内容的提问来源于stack exchange,提问作者FinnDevSlavGod420

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 19:15:12