Hey guys so I am currently making a enemy AI for a 2D Platformer. I dont know how I havent been able to find an answer to this cause it seems fairly simple. The enemy sprite hovers back and forth and if the player collides with it, the player respawns at the beginning of the level. The Code works well but the enemy just hovers back and forth. I created two animations, One called “Left” and one called “Right” as you can guess, they are of the enemy walking, facing that direction. Im having trouble incorporating them into my script though.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HazardMove : MonoBehaviour{
private ObjectMove player; //references the "player" for trigger
public Transform start; //references the location the player will respawn on contact
public float amounttomovex;
public float speed;
private float currentposx;
private float currentposy;
private int facing;
public Animation anim; //for switching the two animatons
void Start()
{
player = FindObjectOfType<ObjectMove>();
currentposx = gameObject.transform.position.x;
facing = 0;
}
void Update()
{
if (facing == 1 && gameObject.transform.position.x < currentposx - amounttomovex)
{
facing = 0;
}
if (facing == 0 && gameObject.transform.position.x > currentposx)
{
facing = 1;
}
if (facing == 0)
{
transform.Translate(Vector2.right * speed * Time.deltaTime);
anim.CrossFade("Right");
}
else if (facing == 1)
{
transform.Translate(-Vector2.right * speed * Time.deltaTime);
anim.CrossFade("Left");
}
}
As you can see at the last If and Else If statements, I tried using anim.CrossFade(“Left”); and Right. This doesn’t seem to do anything, the animations don’t play at all and the sprite just hovers back and forth. Do I have these animations in the wrong spot or should they be in the code differently? Im sure its something in the Transform.Translatet that is interfering but when I take parts of it out, it stops hovering back and forth. Ive been stuck on this for a few days now so if anyone has any tips or knows a better way I should be attacking this from, I greatly appreciate it!