How many ways are there to clamp 3d objects?
I am trying to understand and learn more about Unity better by creating simple games, this time I was trying to create a 3d player that can move around all over except the y axis, because the camera is looking downwards to the player. Anyways I had a problem, I am still trying to create a script where the player moves around freely (still trying to find a way), when a new problem occured: the player is going outside the bounds of the screen when moving. I managed to find a tutorial about it here: https://www.youtube.com/watch?v=ailbszpt_AI&t=184s ,
public class ScreenBoundaries : MonoBehaviour
{
private Vector2 screenBounds;
// Start is called before the first frame update
void Start()
{
screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z));
}
// Update is called once per frame
void LateUpdate()
{
Vector3 viewPos = transform.position;
viewPos.x = Mathf.Clamp(viewPos.x, screenBounds.x, screenBounds.x * -1);
viewPos.y = Mathf.Clamp(viewPos.y, screenBounds.y, screenBounds.y * -1);
transform.position = viewPos;
}
}
but there was a problem for me, this was for 2d objects and not 3d. Because of this my player kept glitching and stuttering. I spent many hours trying to figure out how to solve this along with trying to understand how this works. After a few days, I managed to find the answer which is here:
using UnityEngine;
using System.Collections;
public class Example : MonoBehaviour {
void Update() {
Vector3 pos = Camera.main.WorldToViewportPoint (transform.position);
pos.x = Mathf.Clamp01(pos.x);
pos.y = Mathf.Clamp01(pos.y);
transform.position = Camera.main.ViewportToWorldPoint(pos);
}
}
credit goes to @robertbu , which is so simple as opposed to the long answers that I have seen and had trouble implementing. My questions is this: How many ways are there to clamp 3d objects? What is the difference between the long answers when the short code here already solves it? What is the advantage/disadvantage of using the above code I am using right now? and what was wrong with my first code, cause I dont understand.