Home > Blockchain >  Unity 2D - Moving Any Object Between Two (or more) Spaces
Unity 2D - Moving Any Object Between Two (or more) Spaces

Time:09-23

new Unity person, and new coder in general. I'm trying to have an object move back and forth between two spots. I have it right now going from Point 1 to Point 2, but it stops. I tried a do loop, and to call back the Move() function again but it just froze Unity.

I'm guessing I need some sort of Loop, but not sure where to do it? I wouldn't mind having the ability to add more spots as well. I have waypoints in Unity itself, tied to the Object. Thanks!

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

public class ZombiePathing : MonoBehaviour
{
    [SerializeField] List<Transform> waypoints;
    [SerializeField] float moveSpeed = 2f;
    int waypointIndex = 0;

    
 
    void Start()
    {
        transform.position = waypoints[waypointIndex].transform.position;
    }

    // Update is called once per frame
    void Update()
    {
        Move();
    }

    private void Move()
    {
        if (waypointIndex <= waypoints.Count -1)
        {
             var targetPosition = waypoints[waypointIndex].transform.position;
             var movementThisFrame = moveSpeed * Time.deltaTime;
            transform.position = Vector2.MoveTowards
                (transform.position, targetPosition, movementThisFrame);
            if (transform.position == targetPosition)

            {
                waypointIndex  ;
            }


        }
        
         
     }
} 

CodePudding user response:

just add an index equal to 1 or -1 depends on the current transform, I wrote this code very quickly so it's unsorted, and I do my best to make it very close to your code with some edits.

  using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class ZombiePathing : MonoBehaviour
    {
        [SerializeField] List<Transform> waypoints;
        [SerializeField] float moveSpeed = 2f;
        Vector3 targetPosition;
        int waypointIndex = 0;
        int index = 1;
        void Start()
        {
            transform.position = waypoints[waypointIndex].position;
            UpdateTransform();
        }
        void Update()
        {   transform.position = Vector2.MoveTowards
            (transform.position, targetPosition, moveSpeed * Time.deltaTime);
            if (transform.position == targetPosition) UpdateTransform();
        }
    
        private void UpdateTransform()
        {
             waypointIndex  = index;
             targetPosition = waypoints[waypointIndex].position;
             if (waypointIndex >= waypoints.Count -1) index = -1;
             else if (waypointIndex <= 0 && index == -1)index = 1;
        }
    } 
  • Related