Move towards has object moving in another direction

using UnityEngine;

public class BallLogic : MonoBehaviour
{
    public Vector3 offset;
    public float ballSpeed;
    private Transform target;
    private Rigidbody rb;
    public bool goingToTarget;
    void Start()
    {
        if (target == null)
        {
            target = GameObject.Find("QB").transform;
        }

        rb = GetComponent<Rigidbody>();
    }

    void Update()
    {
        // if close to target, no longer going to target as has been caught
        if (Vector3.Distance(transform.position, target.position) < .5)
        {
            goingToTarget = false;
        }

        //
        if (goingToTarget)
        {
            //   rb.velocity = Vector3.MoveTowards(transform.position, target.position, Mathf.Infinity)* ballSpeed * Time.deltaTime;
            rb.velocity = Vector3.MoveTowards(transform.position, target.position, ballSpeed * Time.deltaTime);
            Debug.Log(target.position);
        } else {
            target.gameObject.GetComponent<PathfindingScript>().hasBall = true;
            transform.position = target.position + offset;
            transform.rotation = target.rotation;
        }
    }

    public void GoToTarget(Transform targetz)
    {
        // I tried having it here but had the same issue
        goingToTarget = true;
        target = targetz;
       
        transform.position = transform.position + offset + new Vector3(0, 0, 2);
    }

When the object is told to go to the target it goes in the opposite direction. I couldn’t find anything online about other people having this issue. I tried having it look at the target and then move forward but I had a similar issue.

You’re using the wrong tools in the wrong way here.

rb.velocity = Vector3.MoveTowards(transform.position, target.position, ballSpeed * Time.deltaTime);

This line of code makes no sense for several reasons

  • MoveTowards with two positions as parameters is going to result in a position vector.
  • A position vector is not suitable to use as a velocity. Velocity requires a direction and a magnitude. Not a position.
  • Time.deltaTime likewise is not suitable here

If you want to give your object a velocity towards a certain object you would do this:

// Calculate the difference vector from our Rigidbody to the target
Vector3 diff = target.position - rb.position;
// Normalize the difference to get a unit direction vector
Vector3 direction = diff.normalized;

// The desired velocity will be direction * speed.
rb.velocity = direction * ballSpeed;
4 Likes

Thank you appreciate it!