Skip to content

Instantly share code, notes, and snippets.

@kinifi
Created July 27, 2016 17:00
Show Gist options
  • Save kinifi/8645a38feea9f9ce6262df5c87109aa8 to your computer and use it in GitHub Desktop.
Save kinifi/8645a38feea9f9ce6262df5c87109aa8 to your computer and use it in GitHub Desktop.
using UnityEngine;
using System.Collections;
public class Movement : MonoBehaviour {
//the Axis of the joystick
private float horAxis, vertAxis;
//components
private Rigidbody _rigid;
//the last rotation passed from the joystick
private Quaternion m_lastRotation;
[Header("Player Config")]
public float m_movementSpeed = 0.1f;
// Use this for initialization
void Start () {
//get the components
_rigid = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update () {
horAxis = Input.GetAxis("Horizontal");
vertAxis = Input.GetAxis("Vertical");
//transform.eulerAngles = new Vector3( 0, Mathf.Atan2( vertAxis, horAxis) * -180 / Mathf.PI, 0 );
float angle = Mathf.Atan2(horAxis, vertAxis) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(new Vector3(0, angle, 0));
//check if the joystick is pushed forward
if(horAxis > 0.5f || horAxis < -0.5f || vertAxis > 0.5f || vertAxis < -0.5f)
{
//save the last rotation
m_lastRotation = transform.rotation;
//move the player
transform.position += transform.forward * m_movementSpeed;
}
else
{
//rotate the player to the last rotation it used
transform.rotation = m_lastRotation;
//check if we should stop the player velocity
if(_rigid.velocity != Vector3.zero)
{
//stop the player
_rigid.velocity = Vector3.zero;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment