Skip to content

Instantly share code, notes, and snippets.

@codeimpossible
Last active December 30, 2015 10:49
Show Gist options
  • Save codeimpossible/7818961 to your computer and use it in GitHub Desktop.
Save codeimpossible/7818961 to your computer and use it in GitHub Desktop.
PlayerController from a unity game I am making.
using System;
using UnityEngine;
namespace FragCastle.GameObjects
{
public class Actor : MonoBehaviour
{
private const string HorizontalAxis = "Horizontal";
private Animator _animator;
private bool _flipped = false;
public Vector2 speed = new Vector2( 1, 1 );
public Animator Animator
{
get
{
return _animator;
}
}
public Single GetXInput()
{
return Input.GetAxis( HorizontalAxis );
}
public void Awake()
{
_animator = GetComponent<Animator>();
}
public virtual void Update()
{
var inputX = GetXInput();
var localScaleX = Mathf.Abs( transform.localScale.x );
// flip the character if they are running left!
if( inputX < 0f )
_flipped = true;
if( inputX > 0f )
_flipped = false;
localScaleX *= _flipped ? -1 : 1;
transform.localScale = new Vector3( localScaleX, transform.localScale.y, transform.localScale.z );
}
}
}
using FragCastle.GameObjects;
using UnityEngine;
public class PlayerController : Actor
{
public override void Update()
{
var inputX = GetXInput();
if( Input.GetKeyDown(KeyCode.Space) )
{
Animator.SetTrigger("Shooting");
}
else
{
Animator.SetBool( "Moving", Mathf.Abs(inputX) > 0f );
}
var status = Animator.GetCurrentAnimatorStateInfo( 0 );
if( inputX != 0f && !status.IsName( "player_shoot" ) )
{
var movement = new Vector3( speed.x * inputX, 0, 0 );
movement *= Time.deltaTime;
transform.Translate( movement );
}
base.Update();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment