My approach to moving platforms

Before the previous lecture came up, I added a moving platform but approached the problem a completely different way.

My idea was to have two main factors, a vector which is the distance I want to move the platform in, a speed for the speed of the platform, and a compensation radius for floating point comparison, which Ben talks about in the next few lectures.

The idea is the platform moves to the destination at a fixed rate, which is the speed we specified. Once it gets there, it’ll flip direction until we’re back at the original position, and we repeat the pattern. This isn’t as smooth as using sin waves, but thought I’d share it anyways.

using UnityEngine;

[DisallowMultipleComponent]
public class MovingPlatformOld : MonoBehaviour {

[SerializeField] float speed;
[SerializeField] Vector3 distance;
[SerializeField] float compensationRadius;
Vector3 originalPosition;
Vector3 currentDirection;
Vector3 newPosition;

// Use this for initialization
void Start () {

    originalPosition = transform.position;
    newPosition = originalPosition + distance;
    currentDirection = distance;
    transform.Translate(currentDirection * speed * Time.deltaTime, Space.World);

}

// Update is called once per frame
void Update() {

    Vector3 currentPosition = transform.position;
    float distanceBetweenNewCurrent = Vector3.Distance(newPosition, currentPosition);
    float distanceBetweenCurrentOriginal = Vector3.Distance(currentPosition, originalPosition);
    transform.Translate(currentDirection * speed * Time.deltaTime, Space.World);

    if (-compensationRadius <= distanceBetweenNewCurrent && distanceBetweenNewCurrent <= compensationRadius) {
        currentDirection = -distance;
    }

    else if(distanceBetweenCurrentOriginal <= compensationRadius && distanceBetweenCurrentOriginal >= -compensationRadius) {
        currentDirection = distance;
    }
}

}

Privacy & Terms