How to move an object on a moving platform with the platform
I've got a moving platform working courtesy of a previous answer. Now I need to know how I can get an object that is on this platform moving with the same velocity as the platform.
public class MovingPlatformManager : MonoBehaviour
{
public List<Transform> m_PlatformWaypoints = new List<Transform>();
public int m_WaypointIndex;
public float m_PlatformSpeed;
public float m_PlatformCurrentSpeed;
public float m_PlatformMaxSpeed;
public float m_PlatformAcc;
public float m_PlatformDelay;
public float m_PlatformCurrentDelay;
public Vector2 waypointPosition;
void Awake ()
{
m_PlatformAcc = m_PlatformMaxSpeed / m_PlatformSpeed;
m_WaypointIndex = 0;
}
void Update ()
{
if (m_WaypointIndex <= m_PlatformWaypoints.Count - 1)
{
waypointPosition.Set(m_PlatformWaypoints[m_WaypointIndex].position.x, m_PlatformWaypoints[m_WaypointIndex].position.y);
if (Vector2.Distance(gameObject.transform.position, waypointPosition ) > 0f)
{
m_PlatformCurrentSpeed += m_PlatformAcc * Time.deltaTime;
m_PlatformCurrentSpeed = Mathf.Min(m_PlatformCurrentSpeed, m_PlatformMaxSpeed);
gameObject.transform.position = Vector2.MoveTowards(gameObject.transform.position, waypointPosition, m_PlatformCurrentSpeed);
}
else
{
m_PlatformCurrentSpeed = 0f;
gameObject.transform.position = waypointPosition;
if(m_PlatformCurrentDelay == 0f)
{
m_PlatformCurrentDelay = m_PlatformDelay;
}
if (m_PlatformCurrentDelay > 0f)
{
m_PlatformCurrentDelay -= 1f * Time.deltaTime;
}
if (m_PlatformCurrentDelay <= 0f)
{
m_WaypointIndex++;
m_PlatformCurrentDelay = 0f;
if (m_WaypointIndex == m_PlatformWaypoints.Count)
{
m_WaypointIndex = 0;
}
}
}
}
}
void OnTriggerStay2D (Collider2D ground)
{
//Move objects on platform with platform
}
Here's the script for the platform. The objects that need to be moved by this platform are on a ground layer. Having the script move anything on the ground layer that is on the platform would be ideal.
Would making your object the child work for you? Then moving the platform will move the object.
void OnTriggerStay2D (Collider2D other)
{
if(other.transform.parent != transform) {
other.transform.parent = transform;
}
}
void OnTriggerExit2D(Collider2D other)
{
if(other.transform.parent == transform) {
other.transform.parent = null;
}
}
Something like this?
Never$$anonymous$$d that is mostly correct except you'll. want
ground.GetComponent<Collider2D>().transform.root.GetChild(1).SetParent(null);
on exit.
Your answer
Follow this Question
Related Questions
Stepping on game object moves quickly to react 0 Answers
Why won't my 2D Sprite Move? 1 Answer
How can I make the character jump between the boxes? 0 Answers
Homing attack suggestion 0 Answers