나는 당신이 Collider2D을 사용났습니다. transform.Translate
대신 Rigidbody2D.MovePosition
을 사용해야합니다. 그렇지 않으면 transform.Translate
을 사용하면 문제가 발생할 수 있습니다.
1 최종 이동 위치 .Take 및 1의 결과로 Mathf.Clamp
.Apply Camera.main.WorldToViewportPoint
2 한계와 ViewPortPoint 새로운 위치로 변환한다.
. 으로 ViewPortPoint를 다시 월드 지점으로 변환하십시오.
. 마지막으로 Rigidbody2D.MovePosition
으로 이동하십시오.
아래 코드는 this에서 화면 경계에 대한 제한을 포함하도록 수정되었습니다.
이동Rigidbody
없이 :
충돌 물리학이 필요하지 않은 경우에만 사용 :
public float speed = 100;
public Transform obj;
public void Update()
{
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
//Move only if we actually pressed something
if ((h > 0 || v > 0) || (h < 0 || v < 0))
{
Vector3 tempVect = new Vector3(h, v, 0);
tempVect = tempVect.normalized * speed * Time.deltaTime;
Vector3 newPos = obj.transform.position + tempVect;
checkBoundary(newPos);
}
}
void checkBoundary(Vector3 newPos)
{
//Convert to camera view point
Vector3 camViewPoint = Camera.main.WorldToViewportPoint(newPos);
//Apply limit
camViewPoint.x = Mathf.Clamp(camViewPoint.x, 0.04f, 0.96f);
camViewPoint.y = Mathf.Clamp(camViewPoint.y, 0.07f, 0.93f);
//Convert to world point then apply result to the target object
obj.position = Camera.main.ViewportToWorldPoint(camViewPoint);
}
이동 개체Rigidbody2D
과 : 충돌 물리학이 경우
가
사용 필수 :
public float speed = 100;
public Rigidbody2D rb;
public void Update()
{
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
//Move only if we actually pressed something
if ((h > 0 || v > 0) || (h < 0 || v < 0))
{
Vector3 tempVect = new Vector3(h, v, 0);
tempVect = tempVect.normalized * speed * Time.deltaTime;
//rb.MovePosition(rb.transform.position + tempVect);
Vector3 newPos = rb.transform.position + tempVect;
checkBoundary(newPos);
}
}
void checkBoundary(Vector3 newPos)
{
//Convert to camera view point
Vector3 camViewPoint = Camera.main.WorldToViewportPoint(newPos);
//Apply limit
camViewPoint.x = Mathf.Clamp(camViewPoint.x, 0.04f, 0.96f);
camViewPoint.y = Mathf.Clamp(camViewPoint.y, 0.07f, 0.93f);
//Convert to world point then apply result to the target object
Vector3 finalPos = Camera.main.ViewportToWorldPoint(camViewPoint);
rb.MovePosition(finalPos);
}
두 개의 빈 게임 개체를 각 극단 모서리 (왼쪽 하단, 오른쪽 위)에 배치하십시오. 그런 다음 사용자 위치를 사용하여 사용자 이동을 고정시킵니다. 또는 당신이 마치 한 차원으로 움직이는 것처럼 보이면, x = Mathf.Clamp (x, minX, maxX); – Everts