Mar 20

Simplified SeekSteer and made my own script for moving objects between waypoints. The MovingPlatform now works much better.

/**
 * Attach to object. Moves object between waypoints.
 */
using UnityEngine;
using System.Collections;

public class WaypointsMover : MonoBehaviour {
    public Transform[] waypoints;
    public float waypointRadius = 1.0f;
    public bool loop = true;
    public float speed = 2.0f;

    private Vector3 currentHeading,targetHeading;
    private int targetwaypoint;
    private Transform _transform;

    protected void Start () {
		enabled = false;
        _transform = transform;
        if(waypoints.Length <= 0) {
            Debug.Log("No waypoints on " + name);
            enabled = false;
        }
        targetwaypoint = 0;
    }

    protected void Update() {
        if(Vector3.Distance(_transform.position, waypoints[targetwaypoint].position) <= waypointRadius) {
            targetwaypoint++;
            if(targetwaypoint >= waypoints.Length) {
                targetwaypoint = 0;
                if(!loop)
                    enabled = false;
            }
        }
		_transform.position = Vector3.MoveTowards(_transform.position, waypoints[targetwaypoint].position, Time.deltaTime * speed);
    }

    // Draws red line between waypoints, and sphere with radius
    public void OnDrawGizmos() {
        if(waypoints == null)
            return;

        for(int i=0;i< waypoints.Length;i++) {
    	    Gizmos.color = new Color(0.9f, 0, 0, 0.3f);
			Gizmos.DrawSphere(waypoints[i].position, waypointRadius);
	        Gizmos.color = Color.red;
            Vector3 pos = waypoints[i].position;
            if(i>0) {
                Vector3 prev = waypoints[i-1].position;
                Gizmos.DrawLine(prev,pos);
            }
        }
    }
}

Comments are closed.