- Home /
Enemy ia fliping when hitting object
Hi, I want my enemies to flip and go the opposite direction they are comming from, so far when they hit Bush, and Bush2 it works, but I also want to do that when hitting an enemy, ty!
public float speed;
Rigidbody2D rb2D;
SpriteRenderer sprite;
private bool canMove;
// Use this for initialization
void Start () {
rb2D = GetComponent<Rigidbody2D> ();
sprite = GetComponent<SpriteRenderer> ();
int rand = Random.Range(0, 2);
if (rand == 0)
{
speed = -speed;
}
}
// Update is called once per frame
void Update () {
if (canMove == true) {
transform.Translate (speed * Time.deltaTime, 0, 0);
}
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Bush2") {
sprite.flipX = true;
speed = -1;
}
if (collision.gameObject.tag == "Bush") {
sprite.flipX = false;
speed = -1;
}
if (collision.gameObject.tag == "Enemy") {
sprite.flipX = true;
speed = -1;
}
if (collision.gameObject.CompareTag ("Ground"))
{
canMove = true;
}
}
}
Answer by melsy · Apr 19, 2018 at 03:45 AM
Im changing a bit of the code to make it a little more efficient and versatile.
Add at the top using System.Collections.Generic;
Then in the class add this at the top [SerializeField] List tags = new List(); int tagLength;
Add this to start tagLength = tags.Count;
Change the on CollisionEnter to this string tag; void OnCollisionEnter(Collision other) { tag = other.gameObject.tag; for (int i = 0; i < tagLength; i++) { if(tag == tags[i]) { sprite.flipX = true; speed = -1; } } }
Then in the Inspector add all the tags you want to the tags list . Every tag string you put in there will now change the direction.
Answer by Priyanka-Rajwanshi · Apr 19, 2018 at 04:58 AM
@ThunderAce I would suggest you to use
if (collision.gameObject.tag == "Enemy") {
sprite.flipX = !sprite.flipX ;
speed = -speed;
}
This way if the enemy is going in X Direction, after intercepting an enemy, it would go in -x direction and vice-versa.
Your answer
Follow this Question
Related Questions
How To Deactivate Enemy Shooting 1 Answer
Enemy AI Lagging 0 Answers
Why do the AI get caught on trees? 0 Answers
how do i make enemy ai chase player 0 Answers