c# – Setting a limit to how far my player can move in Unity3D?
If I want my player to only be able to run a short distance before stopping, or in this example climb an object a set distance before falling back to the ground, how would I approach implementing that?
My main idea was to use a while loop where I have a set time value and then use Time.time to make sure that once my player has been climbing for 3 seconds, turn the moveVertically bool false.
The other idea was to have a Raycast shoot forward from the center of my player and if it no longer hits an object in front of it then my player falls down, but that felt pretty clunky and not smooth at all.
// Inside Update, and outside of isGrounded
bool raycast1 = (Physics.Raycast(transform.position + transform.up * -0.8f, transform.forward, 0.6f));
bool raycast2 = (Physics.Raycast(transform.position + transform.up * .5f, transform.forward, 0.6f));
if (raycast1 && raycast2) // Two Raycasts that shoot a short distance forward
{
moveVertically = true;
}
if (moveVertically)
{
if (Input.GetKey(KeyCode.W) && Input.GetKey(KeyCode.Space))
{
controller.Move(Vector3.up * Time.deltaTime * verticalSpeed); // Climb up an object
}
}
So essentially if my character controller component is 2f in height (default height) and I have a climbable object that is 10f in height, my player should only be able to climb less than half of that before not being able to any further and then falling to the ground.
Read more here: Source link
