Search code examples
randomunity-game-engineartificial-intelligenceunityscript

Random movement attempt


I'm trying to make my bear walk randomly when the player is not in it's range. I wanted it to randomly select the its rotation in y axis and then move it forward and after some time switch the rotation randomly again.

The thing is that I don't really know how could I assign him a random rotation. So how do I do this?

I finally managed to do this, here's the working code:

var timeToChangeDirection : float = 60;
private var angle : Vector3;

var damping : float = 6.0;

var controller : CharacterController;

function Update()
{
    distance = Vector3.Distance(target.position, transform.position);

    if(distance > aggroRange)
    {
        moveSpeed = 1;
        timeToChangeDirection -= 0.1;

        if (timeToChangeDirection <= 0) 
        {
            ChangeDirection();
        }

        controller.Move(transform.forward * Time.deltaTime);
        animation["Run"].speed = 0.25;
        animation.Play("Run");
    }

function ChangeDirection()
{
    angle = Vector3(transform.rotation.x, Random.Range(-359, 359), transform.rotation.y);
    transform.Rotate(angle);
    timeToChangeDirection = 60;
}

Solution

  • Okay. I've managed to do it after all. Here's the code if anyone is interested:

    var timeToChangeDirection : float = 60;
    private var angle : Vector3;
    
    var damping : float = 6.0;
    
    var controller : CharacterController;
    
    function Update()
    {
        distance = Vector3.Distance(target.position, transform.position);
    
        if(distance > aggroRange)
        {
            moveSpeed = 1;
            timeToChangeDirection -= 0.1;
    
            if (timeToChangeDirection <= 0) 
            {
                ChangeDirection();
            }
    
            controller.Move(transform.forward * Time.deltaTime);
            animation["Run"].speed = 0.25;
            animation.Play("Run");
        }
    
    function ChangeDirection()
    {
        angle = Vector3(transform.rotation.x, Random.Range(-359, 359), transform.rotation.y);
        transform.Rotate(angle);
        timeToChangeDirection = 60;
    }