Moving Platforms (838478)

I am making a 2D platformer in Unity and I want to add moving platforms. My idea is to make the platform change it’s x by the distance between the x positions of two points divided by speed and the same for the y. I can’t find out why but it doesn’t stop when it gets to the other end.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlatformMove : MonoBehaviour
{
    public GameObject Pos1;
    public GameObject Pos2;
    public GameObject Player;
    public int speed;
    float xmove;
    float ymove;
    bool backwards;
    bool player;
    // Start is called before the first frame update
    void Start()
    {
        transform.position = Pos1.transform.position;
        backwards = false;
        xmove = (Pos2.transform.position.x - transform.position.x)/speed*Time.deltaTime;
        ymove = (Pos2.transform.position.y - transform.position.y)/speed*Time.deltaTime;
        player = false;
    }

    // Update is called once per frame
    void Update()
    {
        if ((backwards)&&(transform.position==Pos1.transform.position))
        {
            backwards = false;
        }
        else
        {
            if ((!backwards)&&(transform.position==Pos2.transform.position))
            {
                backwards = true;
            }
        }
        if (backwards)
        {
            transform.position = new Vector3(transform.position.x - xmove, transform.position.y - ymove, transform.position.z);
            if(player)
            {
                Player.transform.position = new Vector3(Player.transform.position.x - xmove, Player.transform.position.y - ymove, Player.transform.position.z);
            }
        }
        else
        {
            transform.position = new Vector3(transform.position.x + xmove, transform.position.y + ymove, transform.position.z);
            if(player)
            {
                Player.transform.position = new Vector3(Player.transform.position.x + xmove, Player.transform.position.y + ymove, Player.transform.position.z); 
            }
        }
    }
    void OnCollisionEnter2D(Collision2D col)
    {
        if ((backwards)&&(col.gameObject.name == "Player"))
        {
            player = true;
        }
    }
    void OnCollisionExit2D(Collision2D col)
    {
        player = false;
    }
}

Any support is greatly appreciated and I don’t mind if I have to change everything but it would be better if not.

The problem is with == it will rarely be equal with floats, due to floats not being precise (0.4 being 0.3999999). So you need to check for it to be approximately in the position.

1 Like

Thankyou