유니티 WorldToScreenPoint를 사용하여 좌우 이동을 제한하는 스크립트

|

키보드로 오브젝트를 이동시 좌우나 앞으로의 이동을 화면 안으로 제한하고 싶을 경우 쓰는 스크립트





Camera.main.WorldToScreenPoint함수의
Camera.main의 의미는 태그가 mainCamera로 설정된 카메라를 의미합니다.
메인카메라를 기준으로 하는 월드 좌표를 스크린 좌표로 변행해주는 함수 입니다.
if문에서는 왼쪽으로 이동시(key < 0 ) 위치를 제한( pos.x > 0) 해주고 오른쪽으로 이동시(key > 0 ) 위치를 제한(pos.x < Screen.width)해주고 있습니다.

이와 같이 오브젝트의 위치를 스크린 좌표로 변환하면 화면 크기에 상관없게 오브젝트의 위치를 제한 할 수 있습니다.




Camera.WorldToScreenPoint


Vector3 WorldToScreenPoint(Vector3 position);
Description

Transforms position from world space into screen space.

Screenspace is defined in pixels. The bottom-left of the screen is (0,0); the right-top is (pixelWidth,pixelHeight). The z position is in world units from the camera.
using UnityEngine;
using System.Collections;

public class Example : MonoBehaviour {
    public Transform target;
    void Update() {
        Vector3 screenPos = camera.WorldToScreenPoint(target.position);
        print("target is " + screenPos.x + " pixels from the left");
    }
}


Trackback 0 And Comment 0