- Home /
Question by
mugen-sosa · Oct 17, 2016 at 05:03 PM ·
transformenemyflip
flip enemy
ive been looking all day but cant find the right answer... i want to my enemy flip based on where is walking, this is my script i hope can help me thx
using UnityEngine;
using System.Collections;
public class EnemieFollow : MonoBehaviour {
public Transform player;
public float moveSpeed;
public float distance;
private float range;
Animator anim;
void Start ()
{
anim = GetComponent<Animator>();
}
void Update ()
{
range = Vector2.Distance(transform.position, player.position);
if(range > distance)
{
Debug.Log("Range");
transform.position = Vector2.MoveTowards(transform.position, player.position, moveSpeed * Time.deltaTime);
anim.Play("Walk");
}
}
}
Comment
Best Answer
Answer by b1gry4n · Oct 17, 2016 at 05:35 PM
Compare the horizontal value of the direction it is moving/targeting/etc. A hacky solution to facing a certain direction without having different sprites is to invert the scale. If you are targeting the player and if your sprite by default faces right...
if(player.position.x > transform.position.x){
//face right
transform.localScale = new Vector3(1,1,1);
}else if(player.position.x < transform.position.x){
//face left
transform.localScale = new Vector3(-1,1,1);
}
The script works, however it also shrinks the enemy - what causes that?
does your scale start at 1? maybe you can try multiplying it by -1 ins$$anonymous$$d.
bool isFacingRight;
if(player.position.x > transform.position.x){
//face right
if(!isFacingRight){
transform.localScale = new Vector3(transform.localScale.x*-1,transform.localScale.y,transform.localScale.z);
isFacingRight=true;
}
}
else if(player.position.x < transform.position.x){
//face left
if(isFacingRight){
transform.localScale = new Vector3(transform.localScale.x*-1,transform.localScale.y,transform.localScale.z);
isFacingRight=false;
}
}