HeroMobility.cs 1.72 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
using UnityEngine;
using System.Collections;

public class HeroMobility : MonoBehaviour {
    public enum Footsteps {
        GRASS,
        WATER
    }

	public float playerSpeed = 1f;
	private Rigidbody2D playerRB;
	Animator anim;
    private Vector2 lastPos;
    public Vector2 deltaPos;
    private float lastFootstep;
    public float footStepDelay = 0.3f;
17 18 19 20 21 22
    public Footsteps footsetps = Footsteps.GRASS;
    private AudioSource audioSource;

    public AudioClip[] grassFootsteps;
    public AudioClip[] waterFootsteps;

23 24 25 26 27 28 29 30 31 32 33 34
    void Start () {
		playerRB = GetComponent<Rigidbody2D> ();
		anim = GetComponent<Animator> ();
        audioSource = GetComponent<AudioSource>();
        lastPos = playerRB.position;
    }

    // Update is called once per frame
    void FixedUpdate () {
		Vector2 input = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
		playerMove (input);
        
35 36 37
        if(deltaPos.magnitude > 0.001f && Time.time > lastFootstep) {
            lastFootstep += footStepDelay;
            Footstep();
38 39 40 41 42 43 44 45 46 47 48
        }
	}

	void playerMove (Vector2 input){
		//Controls hero movement in all 8 directions
		playerRB.MovePosition((Vector2)transform.position + input.normalized*playerSpeed);
        deltaPos = playerRB.position - lastPos;
        lastPos = playerRB.position;

    }

49 50 51 52 53 54 55 56 57
    void Footstep() {
        switch (footsetps) {
            case Footsteps.GRASS:
                audioSource.PlayOneShot(grassFootsteps[Random.Range(0, grassFootsteps.Length)]);
                break;
            case Footsteps.WATER:
                audioSource.PlayOneShot(waterFootsteps[Random.Range(0, waterFootsteps.Length)]);
                break;
        }
58 59
    }
}