Week 10 – Movement Code Version 2

This is the second version of the code. I went back to the root and I wanted to be sure the movement on the forwards – backward axis was properly implemented and it switched direction as needed.

//Movement Version 0.2

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Movement : MonoBehaviour {

    public float _spd = 10f;
    // Speed for the movement. It will vary depending on status (e.g. run, walk/sneak);

    private float _hz;
    // Used to register the horizontal movement

    public Rigidbody _rb;
    // Used to get the rigidbody as a variable;

    private Quaternion _rFacing;
    // Used to change directon when facing  for right

    private Quaternion _lFacing;
    // Used to change direction when facing  for left

    private int _sw;

    // Used for managing the change of direction

    // Use this for initialization
    void Start () {

        _rb = GetComponent <Rigidbody> ();
        // Asigning the Rigidbody to the variable

        // Getting the rotation of the transformation when facing right and reversing it for left facing
        _rFacing = transform.rotation;
        _lFacing = _rFacing * Quaternion.Euler(0f, 180f, 0);

        _sw = 0;

        // Assigning a value for the player when he is facing right

    }
    
    // Update is called once per frame
    void Update () {

        // Assign all the Axis and Buttons to the variables
        _hz = Input.GetAxis (Horizontal);


// Condition for changing facing direction
        if (Mathf.Abs(_hz) > 0f) {
            if (_hz < 0f)
            {
                _sw = 1;
            }
            else {
                _sw = 0;
            }
        }


// Changing the transform for the direction the player is facing
        switch (_sw) {
            case 0:
                transform.rotation = _rFacing;
                break;
            case 1:
                transform.rotation = _lFacing;
                break;
        }

        // The movement takes place, depending on the buttons pressed
                transform.Translate (new Vector3 (0, 0, Mathf.Abs(_hz)) * _spd * Time.deltaTime);

    }
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s