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

如何在给定的Unity Mask脚本中限制Y轴移动范围

Add Y-Axis Movement Limit to Your Mask Script

Got it, let's sort out that Y-axis range restriction for your Mask movement! Here are two simple, practical approaches you can use:

Approach 1: Clamp Position After Movement

This method moves the object first, then pulls it back into the desired range immediately. It's straightforward and works great for most cases:

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

public class Mask : MonoBehaviour {
    // Adjust these values directly in the Unity Inspector
    public float minY = -2f;
    public float maxY = 2f;

    void Start() { }

    void Update() {
        if (Input.GetKey(KeyCode.X)) {
            transform.Translate(Vector3.down * 0.01f);
        }
        if (Input.GetKey(KeyCode.C)) {
            transform.Translate(Vector3.up * 0.01f);
        }

        // Lock the Y position within our defined range
        Vector3 currentPosition = transform.position;
        currentPosition.y = Mathf.Clamp(currentPosition.y, minY, maxY);
        transform.position = currentPosition;
    }
}

How it works:

  • Mathf.Clamp() takes three values: the value to restrict, the minimum allowed value, and the maximum allowed value. It ensures the Y position never goes below minY or above maxY.
  • Making minY and maxY public lets you tweak the range in the Unity Editor without editing code, which is super convenient for testing.

Approach 2: Restrict Movement Before Updating Position

If you want to avoid even a tiny "overstep" beyond the boundary (for smoother movement), calculate the target position first, clamp it, then apply it:

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

public class Mask : MonoBehaviour {
    [SerializeField] private float minY = -2f; // Visible in Inspector but private
    [SerializeField] private float maxY = 2f;
    [SerializeField] private float moveSpeed = 0.01f;

    void Start() { }

    void Update() {
        Vector3 targetPosition = transform.position;

        if (Input.GetKey(KeyCode.X)) {
            targetPosition.y -= moveSpeed;
        }
        if (Input.GetKey(KeyCode.C)) {
            targetPosition.y += moveSpeed;
        }

        // Clamp the Y value BEFORE setting the position
        targetPosition.y = Mathf.Clamp(targetPosition.y, minY, maxY);
        transform.position = targetPosition;
    }
}

Bonus Tip:

Using [SerializeField] instead of public keeps your variables private (following good encapsulation practices) while still letting you adjust them in the Unity Inspector.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 12:57:47