Unity-Technologies / UnityPlayground

A collection of simple scripts to create 2D physics game, intended for giving workshops to a young audience
MIT License
856 stars 163 forks source link

Wander Behaviour #5

Closed Bryan-Legend closed 7 years ago

Bryan-Legend commented 7 years ago

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);
        }
    }
}
ciro-unity commented 7 years ago

I like this one @Lone-Coder, I might "steal" it 😄

With a couple of modifications maybe, I'll probably change the InvokeRepeating for a Coroutine system (I prefer them to Invoke). Also maybe give the option to tell the object to keep near its starting spot by checking the distance from it before applying the force?

But yeah, really good idea, it's a needed script!

ciro-unity commented 7 years ago

I've implemented the script and the corresponding custom inspector. Will be live in the next Git Push. Closing the issue :)