Home > database >  Moving an object towards a position not working properly
Moving an object towards a position not working properly

Time:06-19

I have written a code to get a random transform from my list pathPoints and move my object based on that transform, but what it is doing is getting multiple transforms and trying to move everywhere at once. I want the object to move at one position then get a new position and move there then repeat.

Here is the code:-

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

public class PathFinder : MonoBehaviour

    [SerializeField] List<Transform> pathPoints;
    [SerializeField] Transform pathPrefab;
    [SerializeField] float moveSpeed = 10f;
    [SerializeField] bool isMoving = false;
    [SerializeField] bool isH_Attacking = false;
    Animator anim;
    Transform defaultWayPoint;
    Transform currentTargetPoint;
    

    void Awake() 
    {
        anim = GetComponent<Animator>();
        defaultWayPoint = pathPrefab.GetChild(0);
    }

    void Start()
    {
        currentTargetPoint = pathPoints[Random.Range(0, pathPoints.Count)];
        transform.position = defaultWayPoint.position;     
    }

    void MoveToNextWayPoint()
    {
        if(transform.position != currentTargetPoint.position)
        {
            float delta = moveSpeed * Time.deltaTime;
            transform.position = Vector3.MoveTowards(transform.position, currentTargetPoint.position, delta);
            anim.SetBool("isMoving", true);
            isMoving = true;
        }
        GetNextWayPoint();
    }

    Transform GetNextWayPoint()
    {
        currentTargetPoint = pathPoints[Random.Range(0, pathPoints.Count)];
        Debug.Log(currentTargetPoint.position);
        return currentTargetPoint;
    }

    void Update()
    {
        MoveToNextWayPoint();
    }

*The script is attached to the gameObject which I want to move.

*This is a 2d project.

CodePudding user response:

void MoveToNextWayPoint()
{
    if(transform.position != currentTargetPoint.position)
    {
        float delta = moveSpeed * Time.deltaTime;
        transform.position = Vector3.MoveTowards(transform.position, currentTargetPoint.position, delta);
        anim.SetBool("isMoving", true);
        isMoving = true;
    }
    else
    {
        GetNextWayPoint();
    }
}
  • Related