Hello,
I have been stuck for a couple of days and unable to make a clean script that would move my player along with the platform he is standing on (moving platform) while sustaining the player’s local scale and control to exit or enter the platform.
The first methodology i tried was the one which uses the parent-child relationship (where you set the player as child of the moving platform, consequently the player’s position automatically gets adjusted based on its parent). However, this methodology tends to have have plenty of disadvantages that i might face in the future, in the meantime its only that the Scale of a child always have to be equal to its parent, so if i have a moving platform with scale of 2,2,2, once the player becomes its child, the player will automatically have the scale of 2,2,2 (which is bad).
The second methodology seems to have a higher potential at the beginning, but it does however have one issue. Well, simply do a Raycast from the player’s to his down side, check if the ray collides with the moving platform or not, if it does, then set the flag of the onPlatform = true, and consquently adjust the player position based on the moving platform. Well, it all looks good at this point, but here comes the issue where as long as you are updating the player position based on the moving platform’s position , you will not be able to exit the zone of moving platform, your player is basically STICKING forever to that platform.
See script for the 2nd methodology below:
using UnityEngine;
using System.Collections;
public class TestMovingPlatform : MonoBehaviour {
private bool isOnMovingPlatform;
public Transform player;
public Transform sightStart, sightEnd;
private void Update()
{
RaycastHit2D hit;
hit = Physics2D.Linecast(sightStart.transform.position, sightEnd.transform.position);
Debug.DrawLine(sightStart.transform.position, sightEnd.transform.position, Color.red);
if (hit.transform == null)
{
Debug.Log("Returning");
return;
}
if (hit.transform.tag == ("MovingPlatform"))
{
Debug.Log("hit.transform = MovingPlatform:" );
Transform movingPlatform = hit.collider.transform;
isOnMovingPlatform = true;
}
else
{
Debug.Log("not moving platform but: " + hit.transform.tag);
isOnMovingPlatform = false;
}
if (isOnMovingPlatform)
{
Debug.Log("Adjusting player pos");
player.position = new Vector3(hit.transform.position.x, hit.transform.position.y + offsetToKeepPlayerAbovePlatform, 0);
}
}
}
Any suggestions on how to improve above idea or even a new idea to make a moving platform script that is scale-able and independent?