how do I move object to target position

I have a trigger and when the ball enters I am trying to move it from current position to a set target position.

public class Trigger2 : MonoBehaviour
{

    Vector3 targetPos = new Vector3(-13f, 0f, 0f);
    public float speed = 5f;
   
   

    void OnTriggerEnter(Collider ballCollider)
    {
        if (ballCollider.gameObject.CompareTag("Ball"))
        {
            float step = speed * Time.deltaTime;
            ballCollider.transform.position = Vector3.MoveTowards(ballCollider.transform.position, targetPos, step);
        }
    }
}

tagged object instead moves a little below the trigger but I am trying to get it to go to 13, 0 , 0.

I think that coroutines are what you need. Your code won’t work because 14 line executes only once when ball enters your collider. Instead you need to call coroutine so the ball will move until it reaches its destination. Try this:

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

public class Trigger2 : MonoBehaviour
{
    Vector3 targetPos = new Vector3(-13f, 0.5f, 0f);
    public float speed = 5f;
 
 
    void OnTriggerEnter(Collider ballCollider)
    {
        if (ballCollider.gameObject.CompareTag("Ball"))
        {
            float step = speed * Time.deltaTime;
          
            IEnumerator coroutine = MoveToPosition(ballCollider.gameObject, targetPos, step);
            StartCoroutine(coroutine);
        }
    }
    private IEnumerator MoveToPosition(GameObject go, Vector3 goalPosition,float s)
    {
        while (Vector3.Distance(go.transform.position, goalPosition) > 0.1f)
        {
            go.transform.position = Vector3.MoveTowards(go.transform.position, targetPos, s);
            yield return null;
        }
    }
}
1 Like

thanks man, it is doing exactly what I want now. how did you know coroutines were called for? lol . looks like I will have to read into it.

Because coroutines can run asynchronous to the main thread, where you call your update logic. Usually you can only call code on a per-frame basis. With coroutines you can have code running simultaneous to your update code. That’s basically as simple as i could put it.