I’m very new to Unity and trying to make a 2d platforming game where you solve puzzles using crates and moving platforms. I have made a platform that moves, however when the player or any object with a rigidbody is on the platform it won’t move with it and just stays in place.
This is my code for the moving platform:
using UnityEngine;
using System.Collections;
public class PlatformMovement : MonoBehaviour {
public bool activated;
public GameObject player;
private Vector3 posA;
private Vector3 posB;
private Vector3 nextPos;
[SerializeField]
private float speed;
[SerializeField]
private Transform childTransform;
[SerializeField]
private Transform transformB;
// Use this for initialization
void Start () {
posA = childTransform.localPosition;
posB = transformB.localPosition;
nextPos = posB;
}
// Update is called once per frame
void Update () {
Move();
}
public void OnTriggerStay2D(Collider2D other)
{
Transform thingOnPlatform = other.transform;
thingOnPlatform.position = Vector3.MoveTowards(thingOnPlatform.position, nextPos, (speed * Time.deltaTime));
}
private void Move()
{
childTransform.localPosition = Vector3.MoveTowards(childTransform.localPosition, nextPos, speed * Time.deltaTime);
if (Vector3.Distance(childTransform.localPosition,nextPos) <= 0.1)
{
ChangeDir();
}
}
private void ChangeDir()
{
nextPos = nextPos != posA ? posA : posB;
}
}
I’m using Unity 5.4.0f3 if you need to know.