There isn’t really any problem with this code but I want to know how this works. I can’t wrap my head around it. what is rb.position.x/rb.position.z and boundary. for?
I was following the space shooter tutorial up on Unity and I was confused about it. So I followed the docs but the docs made no sense either.
Thanks for reading this!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class Boundary
{public float xMin, xMax, zMin, zMax;
}
public class Boundary : MonoBehaviour
{
public Boundary boundary;
public float tilt;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
rb.position = new Vector3
(
Mathf.Clamp(rb.position.x, boundary.xMin, boundary.xMax),
0.0f,
Mathf.Clamp(rb.position.z, boundary.zMin, boundary.zMax)
);
}
}
Casiell
2
So what Mathf.Clamp does:
- It takes 3 parameters: your float (rb.position.x), min value (boundary.xMin) and max value (boundary.xMax)
- If your float is smaller than min value, it returns min value
- If your float is bigger than max value, it returns max value
- If your float is somewhere in between, it returns your float
In your case I would imagine it keeps your object position inside of some predefined boundaries. Basically, if it were to go outside of that boundary, it snaps the object back to the borders.