- Home /
Enemy AI Animation Flip when Player is on the right hand side
Basically I have a simple 2D platform game and the enemy follows the player, but when the player is on the right of the enemy, it walks backwards so instead of this I want to say this code:
if the player is on the right hand side of the enemy flip the animation,
otherwise leave it as it is.
I'm very new to programming and this enemy ai script is from one of the forums, this is it so far:
using UnityEngine; using System.Collections;
public class EnemyAi : MonoBehaviour {
public Transform Target;
private GameObject enemy;
private GameObject player;
private float Range;
public float Speed;
// Use this for initialization
void Start () {
enemy = GameObject.FindGameObjectWithTag ("Enemy");
player = GameObject.FindGameObjectWithTag ("Player");
}
// Update is called once per frame
void Update () {
Range = Vector2.Distance (enemy.transform.position, player.transform.position);
if (Range <= 8f) {
transform.Translate(Vector2.MoveTowards (enemy.transform.position, player.transform.position, Range) * Speed * Time.deltaTime);
}
} }
Thanks for your time, I'm sure it's something so simple but I can't find it anywhere, and I know you can flip the animation because I did it for my player, so I just need to know how to do it for the enemy.
Also im using c♯.
Thanks everyone.
Try this and see if it works out.
void Update(){
Vector2 sides = Vector2.right;
Vector2 playerPosistion = player.transform.position - transform.position;
if(Vector2.Dot(sides, playerPosition) < 0){
//flip the animation one side
}
else{
//flip the animation to the other side
}
}
Thank you for your time in replying and helping, unfortunately that didn't work, I got 5 errors in the console that read:
Socket: unable to join multicast group, error: Address already in use(48)
Unable to join player connection multicast group.
Assets/Scripts/EnemyAi.cs(30,47): error CS0103: The name playerPosition' does not exist in the current context Assets/Scripts/EnemyAi.cs(30,36): error CS1502: The best overloaded method match for
UnityEngine.Vector2.Dot(UnityEngine.Vector2, UnityEngine.Vector2)' has some invalid arguments
Assets/Scripts/EnemyAi.cs(30,36): error CS1503: Argument #2' cannot convert
object' expression to type `UnityEngine.Vector2'
I get the playerPosition one because it's not defined anywhere in the script, I did try changing it to try and say "if the gameobject with tag "player" is < 0" but that did nothing.
I'm still stuck, I appreciate the help though, thank you!
Your answer
Follow this Question
Related Questions
2d Top Down Enemy Control (LoZ type) 0 Answers
2D Animation does not start 1 Answer
How can I mirror 2d animation 2 Answers
Reusing animation but they sync 1 Answer