Xmax setting to 720 instead of 16

When trying to use this line:

Vector3 rightMost = Camera.main.ViewportToScreenPoint( new Vector3( 1, 0, distance ) );

my xmax ends up setting to 720, which is considerably larger than it should be, however, if I use this:

Vector3 rightMost = new Vector3( 16, 0, distance );

the ship stops where it should but it is no longer based on the camera.

Full code:

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

    public float speed = 15.0f;
    public float padding = 0.5f;

    public float xmin;
    public float xmax;

	// Use this for initialization
	void Start () {
        float distance = transform.position.z - Camera.main.transform.position.z;
        Vector3 leftMost = Camera.main.ViewportToScreenPoint( new Vector3( 0, 0, distance ) );
        Vector3 rightMost = Camera.main.ViewportToScreenPoint( new Vector3( 1, 0, distance ) );
        // Vector3 leftMost = new Vector3( 0, 0, distance );
        // Vector3 rightMost = new Vector3( 16, 0, distance );
        xmin = leftMost.x + padding;
        xmax = rightMost.x - padding;
    }
	
	// Update is called once per frame
	void Update () {
        if( Input.GetKey( KeyCode.LeftArrow ) ) {
            // transform.position -= new Vector3( shipSpeed * Time.deltaTime, 0, 0 ); // Old version
            transform.position += Vector3.left * speed * Time.deltaTime;
        } else if( Input.GetKey( KeyCode.RightArrow ) ) {
            // transform.position += new Vector3( shipSpeed * Time.deltaTime, 0, 0 ); // Old version
            transform.position += Vector3.right * speed * Time.deltaTime;
        }

        // Restrict player to game space
        float newX = Mathf.Clamp( transform.position.x , xmin, xmax );
        transform.position = new Vector3( newX, transform.position.y, transform.position.z );
    }
}

You need to use Camera.main.ViewportToWorldPoint, not ViewportToScreenPoint.

It’s usually the autocomplete, and I have done that a time or two myself.

Privacy & Terms