Create a gist now

Instantly share code, notes, and snippets.

A big and hacky player control script for a 2d platformer. I use the messengerHelper at the unity wiki located at http://wiki.unity3d.com/index.php?title=Advanced_CSharp_Messenger as a ligherweight message passing mechanism then Send message and C# events. That would be the only dependency.
using System;
using UnityEngine;
using System.Collections;
//todo: Fix Attack Range
public class PlayerControlScript : MonoBehaviour
{
#region Properties
private const string CharacterLayer = "Character";
private const string DefaultLayer = "Default";
private const int AttackOffset = 3;
public float AttackRange = 100;
[HideInInspector]
public bool
facingRight = true;
[HideInInspector]
public bool
jump = false;
[HideInInspector]
public bool
takeDamage = false;
[HideInInspector]
public bool
duck = false;
public float moveForce = 365f; // Amount of force added to move the player left and right.
public float maxSpeed = 5f; // The fastest the player can travel in the x axis.
public float jumpForce = 1000f; // Amount of force added when the player jumps.
public int Health = 100;
[HideInInspector]
public bool
qAttack = false;
[HideInInspector]
public bool
mAttack = false;
private RaycastHit2D Hit;
public SpriteRenderer AttackEffectRender;
private Transform groundCheck; // A position marking where to check if the player is grounded.
//private Transform attackCheck; // A position marking where to check if an enemy is in attackRange;
private bool grounded = false; // Whether or not the player is grounded.
private Animator anim; // Reference to the player's animator component.
#endregion Properties
void Start ()
{
Messenger.AddListener<Enemy,int> ("PlayerHit", OnPlayerHit);
}
void OnPlayerHit (Enemy sender, int damage)
{
Debug.Log ("On Player Hit Fired");
//score = GameObject.Find("Score").GetComponent<Score>();
/*
var sprite = GetComponent<SpriteRenderer> ();
sprite.color = Color.red;
var camera = GameObject.FindGameObjectWithTag ("MainCamera");
Hashtable ht = new Hashtable ();
ht.Add ("x", 2.0f);
ht.Add ("y", 2.0f);
ht.Add ("time", 0.5f);
iTween.ShakePosition (camera, ht);
*/
//anim.SetTrigger ("");
TakeDamage (damage);
//sprite.color = Color.white;
}
void TakeDamage (int damage)
{
Health -= damage;
}
void Awake ()
{
// Setting up references.
groundCheck = transform.Find ("groundCheck");
anim = GetComponent<Animator> ();
}
void Flip ()
{
//Switch the way the player is labelled as facing.
facingRight = !facingRight;
// Multiply the player's x local scale by -1.
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
// Update is called once per frame
void Update ()
{
// The player is grounded if a linecast to the groundcheck position hits anything on the ground layer.
grounded = Physics2D.Linecast (transform.position, groundCheck.position, 1 << LayerMask.NameToLayer ("Ground"));
// If the jump button is pressed and the player is grounded then the player should jump.
if (Input.GetButtonDown ("Jump") && grounded) {
jump = true;
}
// If the fire button is pressed...
if (Input.GetButtonDown ("Fire1") && !qAttack) {
qAttack = true;
this.rigidbody2D.velocity = Vector2.zero;
this.rigidbody2D.angularVelocity = 0.0f;
}
// If the fire button is pressed...
if (Input.GetButtonDown ("Fire2") && !mAttack) {
mAttack = true;
this.rigidbody2D.velocity = Vector2.zero;
this.rigidbody2D.angularVelocity = 0.0f;
}
}
void FixedUpdate ()
{
//AttackEffectRender.sortingLayerName = DefaultLayer;
// Cache the horizontal input.
float h = Input.GetAxis ("Horizontal");
// The Speed animator parameter is set to the absolute value of the horizontal input.
anim.SetFloat ("Speed", Mathf.Abs (h));
// If the player is changing direction (h has a different sign to velocity.x) or hasn't reached maxSpeed yet...
if (h * rigidbody2D.velocity.x < maxSpeed)
// ... add a force to the player.
rigidbody2D.AddForce (Vector2.right * h * moveForce);
// If the player's horizontal velocity is greater than the maxSpeed...
if (Mathf.Abs (rigidbody2D.velocity.x) > maxSpeed)
// ... set the player's velocity to the maxSpeed in the x axis.
rigidbody2D.velocity = new Vector2 (Mathf.Sign (rigidbody2D.velocity.x) * maxSpeed, rigidbody2D.velocity.y);
// If the input is moving the player right and the player is facing left...
if (h > 0 && !facingRight)
// ... flip the player.
Flip ();
// Otherwise if the input is moving the player left and the player is facing right...
else if (h < 0 && facingRight)
// ... flip the player.
Flip ();
if (qAttack) {
OnAttacking ();
AttackEffectRender.sortingLayerName = CharacterLayer;
anim.SetTrigger ("qAttack");
//Debug.Log("Show Attack Effect Range");
qAttack = false;
} else if (mAttack) {
OnAttacking ();
anim.SetTrigger ("mAttack");
//Debug.Log("Show Attack Effect Range");
AttackEffectRender.sortingLayerName = CharacterLayer;
mAttack = false;
} else {
AttackEffectRender.sortingLayerName = DefaultLayer;
}
// If the player should jump...
if (jump) {
// Set the Jump animator trigger parameter.
anim.SetTrigger ("Jump");
// Play a random jump audio clip.
//int i = Random.Range(0, jumpClips.Length);
//AudioSource.PlayClipAtPoint(jumpClips[i], transform.position);
// Add a vertical force to the player.
rigidbody2D.AddForce (new Vector2 (0f, jumpForce));
// Make sure the player can't jump again until the jump conditions from Update are satisfied.
jump = false;
}
}
void OnAttacking ()
{
this.rigidbody2D.velocity = Vector2.zero;
this.rigidbody2D.angularVelocity = 0.0f;
AttackEffectRender.sortingLayerName = CharacterLayer;
var direction = (facingRight) ? Vector2.right : -Vector2.right;
//Debug.Log("Current Postion = "+transform.position);
var dir = (direction.x == Vector2.right.x) ? "right" : "left";
//Debug.Log(string.Format("Attacking in the {0} direction", dir));
//var postionOffset = new Vector2(transform.position.x+(direction.x*AttackOffset),transform.position.y);
var postionOffset = new Vector2 (transform.position.x + (direction.x * AttackOffset), transform.position.y);
Debug.Log (string.Format ("PlayerPosition = {0} Offset x = {1}", transform.position.x, postionOffset.x));
Hit = Physics2D.Raycast (postionOffset, direction, AttackRange);
//Debug.Log(" Postion of collider = "+Hit.transform.position);
if (Hit.collider != null) {
//Debug.Log("Hit with a tag of = "+Hit.collider.tag);
if (Hit.collider.tag == "enemy") {
//Debug.Log("Hit Enemy ");
Messenger.Broadcast ("EnemyHit", this, Hit.collider.gameObject.GetComponent<Enemy> ().GetInstanceID (), 1);
}
}
}
void OnAttackComplete ()
{
AttackEffectRender.sortingLayerName = DefaultLayer;
}
/*
void SetFriction()
{
if (!anim.GetBool("Jump"))
{
` GetComponent<BoxCollider2D> ().sharedMaterial.friction = frictionOnTheGround;
//Debug.Log ("in the air friction =" + GetComponent<BoxCollider2D> ().sharedMaterial.friction);
}
else
{
GetComponent<BoxCollider2D> ().sharedMaterial.friction = frictionInAir;
//Debug.Log("on the ground friction =" + GetComponent<BoxCollider2D> ().sharedMaterial.friction);
}
Debug.Log("Friction is " + GetComponent<BoxCollider2D> ().sharedMaterial.friction);
}*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment