Changing moving direction after hit other object
I know I can simply change the direction by adding "-" in front of the moving speed. However, it will only move 2 directions (e.g, right or left) But I want to make it move **up/down/righ**t after hitting an object on the right, so here is an example:
object move to right
hit on the wall
change direction to randomly select from up/down/ left (if there is nothing on these position)
So here will be the case, if there are another walls on the left and the top of the object, then it will change the direction to "down".
If there are no more spaces around the object, it will stop. here is my code (now it only move back to left when it hits the wall on the right):
public class ghost : MonoBehaviour {
//the speed at which the ghost moves
public float speed = 1.5f;
//has the ghost been launched yet?
private bool launched = false;
public bool moveRight;
//the rigidbody2D attached to the ghost GameObject
public Rigidbody2D rb;
public Transform blockCheck;
public float blockCheckRadius;
public LayerMask whatIsBlock;
private bool hittingBlock;
// Use this for initialization
void Start () {
//get the rigidbody2D attached to the ghost
rb = this.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update () {
//check if the ghost has been launched.
if (launched == false){
//if the launch button has been pushed, launch the ghost.
if (Input.GetButtonDown ("Launch")) {
hittingBlock = Physics2D.OverlapCircle (blockCheck.position, blockCheckRadius, whatIsBlock);
if (hittingBlock)
moveRight = !moveRight;
//Debug.Log ("is this running");
//move to right if moveRight is true, otherwise, turn left
if (moveRight) {
rb.velocity = new Vector2 (-speed, rb.velocity.y);
} else {
rb.velocity = new Vector2 (speed, rb.velocity.y);
}
launched = true;
}
}
}
}
Comment