Skip to content

Wander Behaviour #5

@Bryan-Legend

Description

@Bryan-Legend

This script will make an object wander around.

using UnityEngine;
using System.Collections;

[RequireComponent(typeof(Rigidbody2D))]
public class Wander : Physics2DObject
{
	// These are the forces that will push the object every frame
	// don't forget they can be negative too!
	Vector2 directionAndStrength = new Vector2(1f, 0f);

    public float speed = 2f;

	//is the push relative or absolute to the world?
	public bool relative = true;

    public float DirectionChangeInterval = 2f;

    void Start()
    {
        InvokeRepeating("ChangeDirection", 0, DirectionChangeInterval);
    }

    void ChangeDirection()
    {
        directionAndStrength = Random.insideUnitCircle;
    }
	
	// FixedUpdate is called once per frame
	void FixedUpdate ()
	{
		if(relative)
		{
			rigidbody2D.AddRelativeForce(new Vector2(directionAndStrength.x, directionAndStrength.y) * speed);
		}
		else
		{
			rigidbody2D.AddForce(new Vector2(directionAndStrength.x, directionAndStrength.y) * speed);
		}
	}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions