0
\$\begingroup\$

I have create a enemy AI script. These enemies are animals in my game. What I want is that the enemy can detect the edges of a platform.

using UnityEngine;
using System.Collections;

public class EnemyAI : MonoBehaviour {

    public float walkSpeed = 2.0f;      // Walkspeed
    public float wallLeft = 0.0f;       // Define wallLeft
    public float wallRight = 5.0f;      // Define wallRight

    float walkingDirection = 1.0f;
    Vector2 walkAmount;

    float originalY; // Original float value

    void Start () {
        this.originalY = this.transform.position.y;
    }

    // Update is called once per frame
    void Update () {

        walkAmount.x = walkingDirection * walkSpeed * Time.deltaTime;

        if (walkingDirection > 0.0f && transform.position.x >= wallRight) {
            walkingDirection = -1.0f;
            Flip();
        } else if (walkingDirection < 0.0f && transform.position.x <= wallLeft) {
            walkingDirection = 1.0f;
            Flip();
        }

        transform.Translate(walkAmount);
    }

}

First of I store the original Y value inside a variable, so the object will be positioned on the platform I chose. Then in update it will do the walk animation.

Problem

I am now searching for a solution, so that the gameObject of enemy can detect the edges of the platform and turn away from it.

Looking out for some suggestions!

\$\endgroup\$
1
\$\begingroup\$

I would've added collider around the edges that will collide only with these characters' bodies. Then use OnCollisionEnter event (and maybe also check the tag of the colliding object) to turn around.

Could also use ray-casting... but I like the collider solution better. It's much more reliable.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.