Unity2d move enemy in opposite direction on collision

Hey guys, I can’t for the love of me figure out how to move my, let’s say “Spider” enemy in the opposite direction once it starts moving and collides with a .tag named “Wall”.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SpiderController : MonoBehaviour {

	public float moveSpeed; 
	private bool canMove; 

	public GameObject deatSpiderExplosion; 

	private Rigidbody2D myRigidBody; 

	//new with radius
	public Transform playerCheck;

	public float playerCheckRadius;

	public LayerMask whatIsPlayer;





	// Use this for initialization
	void Start () {

		myRigidBody = GetComponent<Rigidbody2D> ();

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



		canMove = Physics2D.OverlapCircle(playerCheck.position, playerCheckRadius, whatIsPlayer);

		if (canMove) {

			myRigidBody.velocity = new Vector3 (-moveSpeed, myRigidBody.velocity.y, 0f);

		}

	}

	//void OnBecameVisible(){

		//canMove = true;

	//}

	void OnTriggerEnter2D(Collider2D other){

		if (other.tag == "KillPlane") {

			//Destroy (gameObject);

			gameObject.SetActive (false);
		
			Instantiate (deatSpiderExplosion, other.transform.position, other.transform.rotation);

		}

		if (other.tag == "Water") {

			//Destroy (gameObject);

			gameObject.SetActive (false);

			Instantiate (deatSpiderExplosion, other.transform.position, other.transform.rotation);
		}
	}


	void OnEnable(){

		canMove = false; 

	}

}

So basically I have my spider move left once the player becomes visible. Within my world it will keep going left until it hits either the “killPlane” or “water” .tag, and it dies/gets disabled.

I’ve been trying to maybe make a OnCollisionEnter2D and change its x direction/movespeed to be positive, hence moving to the right, but it simply doesn’t work. I don’t necessarily know if it doesn’t work because I put the movement into the Update function.

Any help would be much appreciated. :slight_smile:

Wow… My bad, instant brain fart immediately after I posted this question. I hope my own answer helps anyone out there trying to do the same with an enemy. Within the OnTriggerEnter2D just add what I show below.

void OnTriggerEnter2D(Collider2D other){

		if (other.tag == "KillPlane") {

			//Destroy (gameObject);

			gameObject.SetActive (false);
		
			Instantiate (deatSpiderExplosion, other.transform.position, other.transform.rotation);

		}

		if (other.tag == "Water") {

			//Destroy (gameObject);

			gameObject.SetActive (false);

			Instantiate (deatSpiderExplosion, other.transform.position, other.transform.rotation);
		}

		if (other.tag == "Wall") {

			moveSpeed *= -1; 

		}

	}

The -1 in my case makes the moveSpeed positive, hence moving right on the X axis, and then it will collide again, making the moveSpeed negative again, hence moving left on the X axis. :slight_smile: