- Home /
Question by
natashabibbs · Dec 16, 2017 at 10:12 AM ·
triggeraienemydirectionstate-machine
Enemy (with state machine) cannot target player!!
Hi guys, my project has been blocked by some error in my code. I followed InscopeStudios 2D platformer tutorial ("targeting the player"). In the tutorial, it calls ChangeDirection() to follow the player but the enemy runs away from the player instead. Please help.
Here is my code: using System.Collections; using System.Collections.Generic; using UnityEngine;
public abstract class Character : MonoBehaviour {
[SerializeField]
protected float movementSpeed;
public bool Attack { get; set; }
public Animator MyAnimator { get; private set; }
protected bool facingRight;
// Use this for initialization
public virtual void Start () {
facingRight = true;
MyAnimator = GetComponent<Animator>();
}
// Update is called once per frame
void Update () {
}
public void ChangeDirection()
{
facingRight = !facingRight;
transform.localScale = new Vector3(transform.localScale.x * -1, transform.localScale.y, transform.localScale.z);
}
}
Here is the enemy's code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : Character {
private IEnemyState currentState;
public GameObject Target { get; set; }
public override void Start()
{
base.Start();
ChangeState(new IdleState());
}
void Update()
{
currentState.Execute();
LookAtTarget();
}
private void LookAtTarget()
{
if (Target != null)
{
float xDir = Target.transform.position.x - transform.position.x;
if (xDir < 0 && facingRight ||xDir > 0 && !facingRight)
{
ChangeDirection();
}
}
}
public void ChangeState(IEnemyState newState)
{
if (currentState != null)
{
currentState.Exit();
}
currentState = newState;
currentState.Enter(this);
}
public void Move()
{
MyAnimator.SetFloat("Speed", 1);
transform.Translate(GetDirection() * (movementSpeed * Time.deltaTime));
}
public Vector2 GetDirection()
{
return facingRight ? Vector2.right : Vector2.left;
}
void OnTriggerEnter2D(Collider2D other)
{
currentState.OnTriggerEnter(other);
}
}
Comment