Day 3 Solutions




NPC Example Goomba (collisions)

 
using UnityEngine;

public class NPCExampleGoomba : MonoBehaviour
{
    Vector2 direction;
    public float speed = 2;
    Rigidbody2D rbody;

    // Start is called before the first frame update
    void Start()
    {
        direction = Vector2.right;
        rbody = GetComponent<Rigidbody2D>();
    }

    private void FixedUpdate()
    {
       // get our position and store it as a Vector2 (normally it is a Vector3)
        Vector2 pos2 = new Vector2(transform.position.x, transform.position.y);

       //use rigidbody2D.moveposition to move so we collide with stuff properly
        rbody.MovePosition(pos2 + direction * speed * Time.deltaTime);
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
       //flips our direction so we go back the way we came
        direction *= -1;
    }
}



NPC Example Jitterbug (motion with random.range)


using UnityEngine;

public class NPCExampleJitterbug : MonoBehaviour
{
    Vector2 direction;
    public float speed = 2;
    Rigidbody2D rbody;

    // Start is called before the first frame update
    void Start()
    {
        direction = Vector2.right;
        rbody = GetComponent<Rigidbody2D>();
    }

    private void FixedUpdate()
    {
        //save our current position as a vector2 (normally it is a vector3...)
        Vector2 pos2 = new Vector2(transform.position.x, transform.position.y);

        //randomize our movement direction
        direction = new Vector2(Random.Range(-1f, 1f), Random.Range(-1f, 1f));

        //ensure that our direction vector has a length of 1 by “normalizing” it
        direction.Normalize();
        rbody.MovePosition(pos2 + direction * speed * Time.deltaTime);
    }
}



NPC Example Smooth Jitterbug (motion with noise)


using UnityEngine;

public class NPCExampleSmoothJitterbug : MonoBehaviour
{
    Vector2 direction;
    public float speed = 2;
    Rigidbody2D rbody;

    float seedX;
    float seedY;

    // Start is called before the first frame update
    void Start()
    {
        seedX = Random.Range(0, 100f);
        seedY = Random.Range(0, 100f);
        rbody = GetComponent<Rigidbody2D>();
    }

    private void FixedUpdate()
    {

        Vector2 pos2 = new Vector2(transform.position.x, transform.position.y);
       
        // get a pseudo-random value from 0 to 1 with perlin noise
        float x = Mathf.PerlinNoise(seedX, Time.time);

        //remap our value from (0:1) to (-1:1)
        x = x * 2 - 1f;

       //get a different pseud-random value for y and remap it
        float y = Mathf.PerlinNoise(seedY, Time.time);
       y = y * 2 - 1f;

       //assign our pseudo-random values to a vector2 and moveposition by that amount
        direction = new Vector2(x,y);

        rbody.MovePosition(pos2 + direction * speed * Time.deltaTime);
    }
}