Face and Move Toward Player.

Good Morning All,

I am not a programming expert by any stretch of the imagination, but if there is one thing I know it’s that getting the code to work is the first step and optimizing is the second step.

With that being said I have decided to share all the code I am using for my current project and hope it can help someone or someone can help me make it better. Regardless, the game I am working on is a Platformer/RPG so there will be a lot of systems happening.

The first code piece I would like to share is the MoveTowardPlayer script that determines if the player is on the Left or Right of whatever GameObject this script is attached to and will move the host toward the player. If the player crosses its path, the enemy will flip its X-Axis to face the player.

 

Below is the script I use to accomplish this effect. 
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoveTowardPlayer : MonoBehaviour {

public Transform target;
public float speed;

private void Start()
{

//This finds the GameObject that has the PlayerController script attached.
//This is assuming there is only one PlayerController.
target = FindObjectOfType<PlayerController>().transform;
}

void Update()
{
float step = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, target.position, step);

#region \/-----Face Right-----\/
if(transform.position.x < target.position.x)
{
GetComponent<SpriteRenderer>().flipX = true;
}
#endregion
#region \/-----Face Left-----\/
else if(transform.position.x > target.position.x)
{
GetComponent<SpriteRenderer>().flipX = false;
}
#endregion
}
}

***As of 04/13/18, this is the current script I am using. If I update it I will update this post.***