Hi I’m following a udemy tutorial and making a game called argon assault, for reference since its a popular course I’ve found online someone who has made a version of the game:
The course however does shows a dirty hack for restricting the ship within the screen, And for practice I want to do it using code.
I’ve tried using the code from the following tutorial:
But for some reason the range in which it limits my ship is way larger than my screen and I can’t figure out why, here is my code:
public class PlayerController : MonoBehaviour
{
[SerializeField] float controlSpeed = 30f;
private Vector2 screenBounds;
void Start()
{
screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z));
Debug.Log("Screen bounds: " + screenBounds);
}
void Update()
{
float xThrow = Input.GetAxis("Horizontal");
float yThrow = Input.GetAxis("Vertical");
float xOffSet = xThrow * Time.deltaTime * controlSpeed;
float rawXPos = transform.localPosition.x + xOffSet;
float clampedXPos = Mathf.Clamp(rawXPos, screenBounds.x * -1, screenBounds.x);
float yOffSet = yThrow * Time.deltaTime * controlSpeed;
float rawYPos = transform.localPosition.y + yOffSet;
float clampedYPos = Mathf.Clamp(rawYPos, screenBounds.y * -1, screenBounds.y);
transform.localPosition = new Vector3(clampedXPos, clampedYPos, transform.localPosition.z);
}
}
I think its also worth mentioning that the ship is a child object to an empty parent object that is used for timeline animations, hence the use of locaposition in some of the code.
Inlcuding the main camera also being a child to the same parent object.