Home > Back-end >  How to make an object that walks forward until it hits a wall?
How to make an object that walks forward until it hits a wall?

Time:10-16

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;
    }
}

CodePudding user response:

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;
    }

UPDATE

As stated in comments, you can also use colliders. To use colliders, you need to add another empty gameObject to your enemy, add a SphereCollider to it. Sphere Collider's radius determines how far you want to detect walls. Then add the following code to the second object:

    // a reference to your enemy controller class
    public Enemy enemy;
    
    private void OnCollisionEnter(Collider other)
    {
        enemy.Rotate();
    }

The OnCollisionEnter is called whenever an object, which has a collider, collides with our object. You need to assign a layer to this new object (wallCheck) and another to your walls. Then from Edit -> Project Settings -> Physics uncheck the collision of wallCheck with any layer other than your walls layer.

  • Related