Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Moving an object towards a position not working properly

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;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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();
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading