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; } }
关键细节解释
- 屏幕边界计算:
ViewportToWorldPoint将视口坐标(0,0对应屏幕左下角,1,1对应右上角)转为世界坐标,不管屏幕分辨率如何变化,都能准确获取当前屏幕的世界范围。 - 玩家尺寸适配:获取玩家的半宽/半高,确保玩家的边缘不会超出屏幕(如果直接限制到屏幕边界,玩家会有一半身体露出屏幕外)。
- 位置限制:用
Mathf.Clamp把玩家的X、Y坐标限制在计算好的范围内,完全替代碰撞体的边界作用,不会和敌人产生任何碰撞交互。
使用注意
- 确保把场景中的主相机拖到脚本的
mainCamera字段上。 - 如果玩家没有SpriteRenderer或Collider2D,手动给
playerHalfWidth和playerHalfHeight赋值合适的数值。
内容的提问来源于stack exchange,提问作者Михаил
相关产品推荐
相关产品推荐

