- Home /
Question by
jhartman1 · Dec 03, 2017 at 03:05 AM ·
c#2d-platformerif-statements
problem making Enemy AI change direction Ontrigger enter or OnCollision
I'm having a issue making a simple AI movement where I make the Object move to one point enter/ touch a collider then turn around to another point like a patrol pattern.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class EnemyControls : MonoBehaviour {
// the game object which spawned us
//private SpiderMovemt SpiderCtrl;
//Used to control how fast the game object moves
[SerializeField]
public float MoveSpeed;
[SerializeField]
public int MaxHit = 1;
public int CurHit;
// Use this for initialization
void Start () {
//find the player game object by name
GameObject Player = GameObject.Find("Player");
//Access the player ship's script component by type
//SpiderCtrl = Player.GetComponent<SpiderMovemt>();
Rigidbody2D rb2d = gameObject.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void FixedUpdate () {
transform.Translate (-MoveSpeed * Time.deltaTime, 0, 0);
}
void OnTriggerEnter (Collider other){
/* what type of object did we collide with?
* is this an enemy?*/
if (other.tag == "PlayerProjectile") {
Debug.Log ("Hit enemy!");
//spawn particles effect on impact
Destroy (gameObject);
}
//collides with player
else if (other.tag == "Player") {
Destroy (gameObject);
}
// hit the player's projectile?
if (other.tag == "PlayerProjectile") {
// a projectile instant kills us
//Destroy(gameObject);
if (CurHit >= MaxHit) {
Destroy (gameObject);
}
}
{
//this is diffrent because I was trying somthing out but still didnt work
if (other.tag == "Left flipper") {
GetComponent<Rigidbody2D> ().position = new Vector2 (GetComponent<Rigidbody2D> ().velocity.x, MoveSpeed);
} else if (other.tag == "Right flipper") {
transform.Translate (-MoveSpeed * Time.deltaTime, 0, 0);
}
}
}
}
I feel like it's not registering the collider
Comment
Best Answer
Answer by jdean300 · Dec 03, 2017 at 08:53 AM
Negate the objects speed in your OnTriggerEnter function. Here is a simplified script example:
private float m_Direction = 1;
public float MoveSpeed;
private void Update() {
transform.Translate(MoveSpeed * m_Direction * Time.deltaTime, 0, 0);
}
private void OnTriggerEnter(Collider other) {
if (other.tag == "Flipper")
m_Direction *= -1;
}