Player Moving

Hey all,

Have an issue where my Player object moves past the X limit to the right, and doesn’t get to the Y limit vertically. Not sure what is wrong as code seem fine to me.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
    [SerializeField] float moveSpeed = 10f;

    float xMin;
    float xMax;
    float yMin;
    float yMax;

    // Start is called before the first frame update
    void Start()
    {
        SetUpMoveBoundaries();
    }

    // Update is called once per frame
    void Update()
    {
        Move();
        
    }

    private void SetUpMoveBoundaries()
    {
        Camera gameCamera = Camera.main;
        xMin = gameCamera.ViewportToWorldPoint(new Vector3(0, 0, 0)).x;
        xMax = gameCamera.ViewportToWorldPoint(new Vector3(1, 0, 0)).x;
        yMin = gameCamera.ViewportToWorldPoint(new Vector3(0, 0, 0)).y;
        xMax = gameCamera.ViewportToWorldPoint(new Vector3(0, 1, 0)).y;

    }

    private void Move()
    {
        var deltaX = Input.GetAxis("Horizontal") * Time.deltaTime * moveSpeed;
        var deltaY = Input.GetAxis("Vertical") * Time.deltaTime * moveSpeed;

        var newXPos = Mathf.Clamp(transform.position.x + deltaX, xMin, xMax);
        var newYPos = Mathf.Clamp(transform.position.y + deltaY, yMin, yMax);

        transform.position = new Vector2(newXPos, newYPos);

    }
}

Hi Dylan,

The boundaries refer to the viewport of the camera, not to the background image. Please zoom out. Where is your camera viewport? In your screenshots, I cannot see the edges of that box, so I assume that the viewport is bigger than the background.

I’ve turned the background off so it’s a little easier to see. The Player object appears retricted to a landscape aspect for some reason.

Does your camera have got the “Main Camera” tag? If so, log the values of the variables into your console and compare them to the player’s position values.

By the way, I’ve just spotted a typo in the SetUpMoveBoundaries method. The last variable should probably be named yMax.

OMG. That typo broke the code. Thanks so much for picking it up. Working perfect now.

Dylan

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms