Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@kinifi
Created April 20, 2017 21:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kinifi/ee84275d8df393081190d162c89e8dab to your computer and use it in GitHub Desktop.
Save kinifi/ee84275d8df393081190d162c89e8dab to your computer and use it in GitHub Desktop.
a 2D free movement playercontroller
/*
* playermovement.cs - attaches rigidbody onto gameobject in editor via RequireComponent, checks inputAxis via Input Axis Names (defaults to Horizontal, Vertical).
* Intention is to move a 2D sprite across the screen via Rigidbody2D
* All properties are private with defaults values. If you need to change a property use the methods to adjust them
* Note: This does not attach a collider or check colliders in anyway. That should be handled separately.
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody2D))]
public class playermovement : MonoBehaviour {
private float m_MovementSpeed = 10.0f;
private bool m_CanMove = true;
private Rigidbody2D m_Rigid;
private string horizontalAxisKey = "Horizontal";
private string verticalAxisKey = "Vertical";
private float m_hAxis, m_vAxis;
// Use this for initialization
void Start () {
m_Rigid = GetComponent<Rigidbody2D> ();
//this is double checking we have this component even though Unity requires it from our RequireComponent above
if (m_Rigid == null) {
Debug.LogError ("Player Rigidbody2D is: " + m_Rigid);
}
}
// Update is called once per frame
void Update () {
//can the player move? If set to false return
if (m_CanMove == false) {
return;
}
//get the axis values
m_hAxis = Input.GetAxis (horizontalAxisKey);
m_vAxis = Input.GetAxis (verticalAxisKey);
//make the player move
m_Rigid.velocity = new Vector2 (m_hAxis, m_vAxis) * m_MovementSpeed;
}
/// <summary>
/// Sets the movement speed.
/// </summary>
/// <param name="speed">Speed.</param>
public void SetMovementSpeed(float speed)
{
m_MovementSpeed = speed;
}
/// <summary>
/// Can the player move?
/// </summary>
/// <param name="CanPlayerMove">If set to <c>true</c> can player move.</param>
public void SetCanMove(bool CanPlayerMove)
{
m_CanMove = CanPlayerMove;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment