I need to make a platform that moves up when the player enters it.
MovingPlatform.cs
public class MovingPlatform : MonoBehaviour
{
[SerializeField]
private Vector3 newPosition;
void Start()
{
newPosition = new Vector3(transform.position.x, transform.position.y + 5, transform.position.z);
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Player"))
{
transform.position = Vector3.MoveTowards(transform.position, newPosition, 4 * Time.deltaTime);
}
}
}
My problem is that the platform moves up only a little and without the player.
The reason, the platform moves only once is due to OnTriggerEnter getting called upon entering the trigger not staying inside it. If you want it to get called constantly, while inside it, use OnTriggerStay instead or assign a boolean value inside OnTriggerEnter and OnTriggerExit methods and change your position inside an Update/FixedUpdate.
Regarding the platform moving without the player, I'm assuming that the player is a physics object and you expect them to be pushed by it. Potential reasons for that happening:
It uses OnCollisionEnter instead of the OnTriggerEnter since it seemed to be more appropriate in this case (Make sure to have a non-trigger collider, if you gonna use it).
using UnityEngine;
public class MovingPlatform : MonoBehaviour
{
[SerializeField]
private Vector3 targetPosition = default;
private bool touchingPlayer = false;
private void Start()
{
targetPosition = new Vector3(
transform.position.x,
transform.position.y + 5f,
transform.position.z);
}
private void FixedUpdate()
{
if (touchingPlayer)
{
transform.position = Vector3.MoveTowards(
transform.position,
targetPosition,
4f * Time.fixedDeltaTime);
}
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Player"))
touchingPlayer = true;
}
private void OnCollisionExit(Collision collision)
{
if (collision.gameObject.CompareTag("Player"))
touchingPlayer = false;
}
}
Instead Of Moving the platform using Vector3s, Create an animation that plays when the player enters a trigger zone.