Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make an object that walks forward until it hits a wall?

I want a character that simply walks forward until it hits a wall, then it does a 180 degree spin and repeats the action.
Making him walk forward is easy, how do I program him hitting the wall?
My current code:

public class Enemy : MonoBehaviour
{

    public float speed = 5;
    public Vector3 userDirection = Vector3.forward;   
    // Update is called once per frame
    void Update()
    {
        transform.position += userDirection * speed * Time.deltaTime;
    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can use raycast to detect walls and avoid them.

Raycast in Unity is a Physics function that projects a Ray into the scene, returning a boolean value if a target was successfully hit

The following code is a simple demenstration of raycast. Distance determine how far you ray is casted and layermask determine which layers ray should detect. Therefore, you must put your walls in a Layer and sit this variable equal to that:

    public float distance;
    public LayerMask wallLayerMask;
    public Vector3 userDirection = Vector3.forward;   

    void Update()
    {
       if (Physics.Raycast(transform.position, userDirection, distance, wallLayerMask))
        {
            // rotate, possibly:
            // userDirection *= -1
        }
      transform.position += userDirection * speed * Time.deltaTime;
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading