0
\$\begingroup\$

In the Update in the else part, I'm trying to move the transform up from its current position on the exit more up by offset.

When the flag bool exit is true I want the transform to move up more by the offset for example if the offset is 7 then move up on the Y more 7. but it's moving up non-stop.

I tried to like this with exitPosition variable for storing at exit: but still, it's moving up non-stop.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Testing : MonoBehaviour
{
    public float speed;
    public float offset;

    private bool exited = false;
    private Vector3 exitPosition;

    private void Start()
    {
        Debug.Log("Position : " + transform.position);
    }

    private void OnTriggerExit(Collider other)
    {
        if (other.name == "Cube")
        {
            Debug.Log("Exited !");
        }

        exitPosition = new Vector3(transform.position.x,
                transform.position.y + offset, transform.position.z);

        exited = true;
    }

    private void Update()
    {
        if (!exited)
        {
            transform.position += Vector3.up * speed * Time.deltaTime;
        }
        else
        {
            transform.position = Vector3.MoveTowards(transform.position, exitPosition, speed * Time.deltaTime);
        }
    }
}
\$\endgroup\$
1
  • 2
    \$\begingroup\$ Note that when you move an object with its transform, instead of a rigidbody, that's handled as a teleportation. The object is removed from the physics scene (calling OnTriggerExit if the object is currently overlapping any applicable colliders), then re-added again (calling OnTriggerEnter if applicable). So these teleports every frame could be calling OnTriggerExit again and again, ratcheting up your target position every time... \$\endgroup\$
    – DMGregory
    May 15, 2021 at 23:52

1 Answer 1

0
\$\begingroup\$

Just make sure your exitPosition is set only once:

private void OnTriggerExit(Collider other)
{
    if (other.name == "Cube" && exited == false)
    {
        Debug.Log("Exited !");
        exitPosition = new Vector3(transform.position.x,transform.position.y + offset,transform.position.z);
        exited = true;
   }
}
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .