Hi everyone. I’m making a moving platform system. The way it works is that I set up waypoints for the platforms, and it lerps between the points. The velocity is then the newPosition (the lerped one) - transform.position. I use that velocity in transform.Translate().
Here is the problem. I currently have 2 waypoints. One at (0,0) (center of box) and the other directly above it. The newPosition computed by lerp is correct, but the translation is jittery, and the object seems to move horizontally a bit (perhaps a floating point error?)
Here is a gif to illustrate this: https://gyazo.com/3c0c24c126b2e356f563a6e0d5e2ca36
Notice how current position is supposed to be at -26 but it goes to -25.9 and -26.1 sometimes.
This ONLY happens when the object is rotated a bit. When it is fully rotated (180), it goes crazy and starts flying off. I’m not sure why it is happening.
Here is the waypoint code (which I basically followed from a youtube tutorial)
Vector2 CalculatePlatformMovement() {
if (Time.time < nextMoveTime) {
return Vector2.zero;
}
fromWaypointIndex %= globalWaypoints.Length;
int toWaypointIndex = (fromWaypointIndex + 1) % globalWaypoints.Length;
float distanceBetweenWaypoints = Vector2.Distance (globalWaypoints [fromWaypointIndex], globalWaypoints [toWaypointIndex]);
percentBetweenWaypoints += Time.deltaTime * speed/distanceBetweenWaypoints;
percentBetweenWaypoints = Mathf.Clamp01 (percentBetweenWaypoints);
float easedPercentBetweenWaypoints = Tools.Ease (percentBetweenWaypoints, easeFactor);
Vector2 newPos = Vector2.Lerp (globalWaypoints [fromWaypointIndex], globalWaypoints [toWaypointIndex], easedPercentBetweenWaypoints);
if (percentBetweenWaypoints >= 1) {
percentBetweenWaypoints = 0;
fromWaypointIndex ++;
if (!cyclic) {
if (fromWaypointIndex >= globalWaypoints.Length-1) {
fromWaypointIndex = 0;
System.Array.Reverse(globalWaypoints);
}
}
nextMoveTime = Time.time + waitTime;
}
print ("current pos: " + (Vector2)transform.position);
return (newPos - (Vector2) transform.position);
}
This method is called in the Update() method, like this:
void Update () {
UpdateRaycastOrigins ();
velocity = CalculatePlatformMovement(); //update the velocity based on the movement vector
CalculatePassengerMovement(velocity); //Check collisions with passengers here, add to list of passengers
MovePassengers (true); //Do all movement of passengers that move BEFORE the platform moves
transform.Translate (velocity); //Move the platform
MovePassengers (false); //Do all movement of passengers that move AFTER the platform moves
}
In the start method, I convert the local waypoints to world global waypoints, like so:
public override void Start () {
base.Start ();
globalWaypoints = new Vector2[localWaypoints.Length];
for (int i = 0; i < localWaypoints.Length; i++) {
globalWaypoints _= localWaypoints *+ (Vector2) transform.position;*_
* }*
* }*