Smoothing out the movement a bit

Yes, I copied what I saw. But I really liked the idea.

2 Likes

Wow that looks really good, mind sharing how you smoothed out the movement?

I got rid of the co-routine and used ‘movetowards’ to smooth out the movement. I played with speed (10) a bit to get the movement rate correct. ‘wayPointPosition’ is a global.

    private void Update()
    {
        moveSmoothly();
        DestroyIfAtEnd();
    }

    private void moveSmoothly()
    {
        float step = speed * Time.deltaTime;

        Vector3 target = new Vector3(
                wayPoint.transform.position.x,
                12f,  // Height of enemy !Important!
                wayPoint.transform.position.z);

        transform.position = Vector3.MoveTowards(transform.position, target, step);

        float distance = Vector3.Distance(transform.position, target);
        if (distance <= 0.1)
        {
            // Jump to next position in list
            if (wayPointPosition < path.Count - 1)
            {
                wayPointPosition += 1;
                wayPoint = path[wayPointPosition];
            }
        }
    }

I was trying to understand your code but I had trouble using it in my game. Could you please provide the full script?

@David_Turull Im sure you’re past this now, but for anyone else in the future heres a full script using @JosephSlone smoothMovement.

using System.Collections.Generic;
using UnityEngine;

public class EnemyMovement : MonoBehaviour
{
    [SerializeField] float secondsBetweenMovements = 2f;
    [SerializeField] List<Waypoint> path;
    [SerializeField] float speed = 10f;
    Waypoint waypoint;
    int wayPointPosition = 0;

    void Start()
    {
        Pathfinder pathfinder = FindObjectOfType<Pathfinder>();
        path = pathfinder.GetPath();
        waypoint = path[wayPointPosition];
    }

    private void Update()
    {
        FollowPath(path);
    }

    void FollowPath(List<Waypoint> path)
    {
        float step = speed * Time.deltaTime;

        Vector3 target = new Vector3(waypoint.transform.position.x, 0f, waypoint.transform.position.z);

        transform.position = Vector3.MoveTowards(transform.position, target, step);
        float distance = Vector3.Distance(transform.position, target);
        if (distance <= 0.1)
        {
            //Jump to next position in list
            if (wayPointPosition < path.Count - 1)
            {
                wayPointPosition++;
                waypoint = path[wayPointPosition];
            }
        }

        print("Ending patrol");
    }
}
1 Like

Privacy & Terms