My code works as in Rick’s video, but if I make a copy of the enemy it stops working.
If I disable the copy’s Game Object, leaving only one enemy, it works.
Video: Unity 2d Course Tilevania - YouTube
PS:(The barrell is the enemy, while the crates are “platform layer”. They are allowed to collide in the matrix and the enemy box collider is trigger.)
PS2:(Sergey is the Player)
This is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyMovement : MonoBehaviour
{
Rigidbody2D enemyBody;
BoxCollider2D enemyCollider;
[SerializeField] float enemyMovementSpeed = 1f;
void Start()
{
enemyBody = FindObjectOfType<Rigidbody2D>();
enemyCollider = FindObjectOfType<BoxCollider2D>();
}
void Update()
{
enemyBody.velocity = new Vector2 (enemyMovementSpeed, 0f);
}
void OnTriggerExit2D(Collider2D other)
{
Debug.Log("Bonk");
enemyMovementSpeed = -enemyMovementSpeed;
FlipEnemy();
}
void FlipEnemy()
{
transform.localScale = new Vector2 (-(Mathf.Sign(enemyBody.velocity.x)), 1f);
}
}
I tried (without success):
-making OnTriggerExit2D private (private void OnTriggerExit2D);
-working with both prefabs and simple Game Object’s copies;
-making the enemies children of two different empty Game Objects.
Thanks!