I have a game with a player controlled by a CharacterController. I also have a MovingPlatform. When the player lands on the moving platform, it becomes a child object of it, so that it should move with the platform. But it does not move - it just stays in place while the platform keeps moving below it. Here is the MovingPlatform code:
public class MovingPlatform : MonoBehaviour {
Transform startPoint = null, endPoint = null;
[SerializeField] float speed = 1f;
private void Start() {
startPoint = transform.parent.Find("StartPoint");
if (!startPoint) throw new Exception("No child with name StartPoint!");
endPoint = transform.parent.Find("EndPoint");
if (!endPoint) throw new Exception("No child with name EndPoint!");
transform.position = startPoint.position;
}
bool moveFromStartToEnd = true;
void Update() {
float deltaX = speed * Time.deltaTime;
Transform targetPoint = (moveFromStartToEnd ? endPoint : startPoint);
transform.position = Vector3.MoveTowards(transform.position, targetPoint.position, deltaX);
if (transform.position == startPoint.position) {
moveFromStartToEnd = true;
} else if (transform.position == endPoint.position) {
moveFromStartToEnd = false;
}
}
private void OnTriggerEnter(Collider other) {
other.transform.SetParent(this.transform);
}
private void OnTriggerExit(Collider other) {
other.transform.SetParent(null);
}
}
When my player with CharacterController lands on the platform, I see that it indeed becomes a child of the platform object, but it still does not move with it.
Interestingly, if I change the Update
to FixedUpdate
, it does work - the CharacterController does move with the platform. I do not understand, why?
MoveTowards()
already contains logic to stop upon reaching the point, so as to not overshoot. 2. The==
comparison operator between Unity'sVector3
structs has some built-in tolerance (about 0.00001), so small differences due to taking different routes to compute the number in floating point precision will get swept under the rug. For most cases, this should be enough, so I wouldn't fret unless we have a demonstrated bug to fix. \$\endgroup\$