Hello,
I am following the Laser Defender portion of the course and tried to implement the ViewportToWorldPoint technique for the boundaries like in the video, but unfortunately my player sprite isn’t quite doing what it is supposed to.
It stays on screen to the top and to the left (though it doesnt go right up to the edge), but it goes off screen on the top and the bottom.
I tried to do some debugging and rewatched the video a couple times but it seems my code is identical so I am not really sure what could be going wrong here.
code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class Player : MonoBehaviour
{
[SerializeField] float moveSpeed = 0.5f;
Vector2 rawInput;
Vector2 minBound; // bottom left of viewport
Vector2 maxBound; // top right of viewport
void Start()
{
InitBounds();
}
void Update()
{
Move();
}
void InitBounds()
{
Camera mainCamera = Camera.main;
minBound = mainCamera.ViewportToWorldPoint(new Vector2(0, 0));
maxBound = mainCamera.ViewportToWorldPoint(new Vector2(1, 1)); // 5.06, 9
}
void Move()
{
Vector2 delta = rawInput * moveSpeed * Time.deltaTime;
Vector2 newPos = new Vector2();
newPos.x = Mathf.Clamp(transform.position.x + delta.x, minBound.x, maxBound.x); // adds the current x and y position of player with the amount we are going to move
newPos.y = Mathf.Clamp(transform.position.y + delta.y, minBound.y, maxBound.y); // and clamps it to not be above the boundary limits
transform.position = newPos;
}
void OnMove(InputValue value)
{
rawInput= value.Get<Vector2>();
}
}
Based on some debugging, my minBound and maxBound are 5.06 and 9 (and their negative counterparts). This holds up when playtesting as well as that is where the values stop moving, but the -9 goes past the camera boundary, and the positive 5.06 goes past the camera boundary.
My camera size is 9 and is set to orthographic projection, I don’t really know what else to check at this stage or why this isnt working, any thoughts would be appreciated!