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

Unity中实现相机边界玩家移动限制(解决Collider适配问题)

Unity玩家相机边界移动限制方案(适配分辨率+不影响敌人)

方案说明

放弃用Box Collider 2D做边界的思路,改用相机视口转世界坐标动态计算屏幕边界,直接限制玩家Transform位置。这种方法既不会和敌人产生碰撞交互,又能自动适配任意手机屏幕分辨率。

修改后的完整代码

using UnityEngine;

public class joystickMove : MonoBehaviour
{
    public Joystick movementjoystick;
    public float playerSpeed;
    public Camera mainCamera; // 拖入场景中的主相机
    private Rigidbody2D rb;
    private Vector2 screenBounds;
    private float playerHalfWidth;
    private float playerHalfHeight;

    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        // 计算屏幕边界的世界坐标
        screenBounds = mainCamera.ViewportToWorldPoint(new Vector3(1, 1, mainCamera.transform.position.z));
        // 获取玩家自身碰撞体/精灵的半尺寸(避免玩家超出屏幕)
        SpriteRenderer sr = GetComponent<SpriteRenderer>();
        if (sr != null)
        {
            playerHalfWidth = sr.bounds.extents.x;
            playerHalfHeight = sr.bounds.extents.y;
        }
        else
        {
            // 如果没有SpriteRenderer,用Collider2D的尺寸
            Collider2D col = GetComponent<Collider2D>();
            if (col != null)
            {
                playerHalfWidth = col.bounds.extents.x;
                playerHalfHeight = col.bounds.extents.y;
            }
        }
    }

    private void FixedUpdate()
    {
        // 原移动逻辑优化:判断方向向量长度,避免y轴为0但x轴有输入的情况
        if (movementjoystick.Direction.magnitude > 0)
        {
            rb.velocity = movementjoystick.Direction * playerSpeed;
        }
        else
        {
            rb.velocity = Vector2.zero;
        }

        // 限制玩家位置在屏幕边界内
        Vector3 clampedPosition = transform.position;
        clampedPosition.x = Mathf.Clamp(clampedPosition.x, -screenBounds.x + playerHalfWidth, screenBounds.x - playerHalfWidth);
        clampedPosition.y = Mathf.Clamp(clampedPosition.y, -screenBounds.y + playerHalfHeight, screenBounds.y - playerHalfHeight);
        transform.position = clampedPosition;
    }
}

关键细节解释

  1. 屏幕边界计算:ViewportToWorldPoint将视口坐标(0,0对应屏幕左下角,1,1对应右上角)转为世界坐标,不管屏幕分辨率如何变化,都能准确获取当前屏幕的世界范围。
  2. 玩家尺寸适配:获取玩家的半宽/半高,确保玩家的边缘不会超出屏幕(如果直接限制到屏幕边界,玩家会有一半身体露出屏幕外)。
  3. 位置限制:用Mathf.Clamp把玩家的X、Y坐标限制在计算好的范围内,完全替代碰撞体的边界作用,不会和敌人产生任何碰撞交互。

使用注意

  • 确保把场景中的主相机拖到脚本的mainCamera字段上。
  • 如果玩家没有SpriteRenderer或Collider2D,手动给playerHalfWidth和playerHalfHeight赋值合适的数值。

内容的提问来源于stack exchange,提问作者Михаил

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 17:24:57