- Home /
How to make a character move with a moving platform? (3D)
Hello everyone! I need to make a player - character controller - move on a moving platform, that has a box collider. I tried to make the player a child of the platform when on it but it doesnt seem to work. How can I implement this feature into my moving platform's script?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class movingPlatform : MonoBehaviour
{
[SerializeField]
float speed;
[SerializeField]
Transform startPoint, endPoint;
[SerializeField]
float changeDirectionDelay;
private Transform destinationTarget, departTarget;
private float startTime;
private float journeyLength;
bool isWaiting;
void Start()
{
departTarget = startPoint;
destinationTarget = endPoint;
startTime = Time.time;
journeyLength = Vector3.Distance(departTarget.position, destinationTarget.position);
}
void Update()
{
Move();
}
private void Move()
{
if (!isWaiting)
{
if(Vector3.Distance(transform.position, destinationTarget.position) > 0.01f)
{
float distCovered = (Time.time - startTime) * speed;
float fractionOfJourney = distCovered / journeyLength;
transform.position = Vector3.Lerp(departTarget.position, destinationTarget.position, fractionOfJourney);
}
else
{
isWaiting = true;
StartCoroutine(changeDelay());
}
}
}
void ChangeDestination()
{
if(departTarget == endPoint && destinationTarget == startPoint)
{
departTarget = startPoint;
destinationTarget = endPoint;
}
else
{
departTarget = endPoint;
destinationTarget = startPoint;
}
}
IEnumerator changeDelay()
{
yield return new WaitForSeconds(changeDirectionDelay);
ChangeDestination();
startTime = Time.time;
journeyLength = Vector3.Distance(departTarget.position, destinationTarget.position);
isWaiting = false;
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Player")
{
other.transform.parent = transform;
}
}
void OnTriggerExit(Collider other)
{
if (other.gameObject.tag == "Player")
{
other.transform.parent = null;
}
}
}
I know this is a frequently asked topic and I'm sorry for that, but I do not know how to make this work. any help's welcome.
Answer by alexc847 · Feb 27, 2021 at 03:41 AM
I'm not going to pretend that I am super good at Unity, and I don't know much about this myself. However, I will provide links that you could explore: https://answers.unity.com/questions/12083/how-to-get-a-character-to-move-with-a-moving-platf.html https://www.youtube.com/watch?v=rO19dA2jksk
Also, my own idea: maybe do something along the lines of parenting the player to the moving platform? Or create a trigger collider and set the player position to the moving platform's whenever the trigger collider detects the player?
Your answer
Follow this Question
Related Questions
How can a player push an object? 5 Answers
Non slippery movement 1 Answer
Gravity and rotation control 0 Answers
AddExplosionForce 0 Answers
Keeping player stationary and let physics affect... 0 Answers