1
Support / Re: Beginning Unity and 2D Toolkit
« on: February 09, 2013, 03:57:57 am »
I'm working through the same book. Very helpful.
This section allows you to view all posts made by this member. Note that you can only see posts made in areas you currently have access to.
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour
{
tk2dAnimatedSprite sprite;
bool walking = false;
bool isColliding = false;
private float moveSpeed = 50;
private int moveDirX;
private int moveDirY;
private Vector3 movement;
private Transform thisTransform;
void Start ()
{
sprite = GetComponent<tk2dAnimatedSprite>();
}
void HitCompleteDelegate(tk2dAnimatedSprite sprite, int clipId)
{
if (!walking)
{
sprite.Play("Idle");
}
}
void PlayIfNotPlaying(string clip)
{
if (!sprite.Playing || sprite.CurrentClip.name != clip)
{
sprite.Play(clip);
}
}
void OnCollisionEnter(Collision collision)
{
Debug.Log("OnCollisionEnter");
isColliding = true;
foreach (ContactPoint contact in collision.contacts)
{
Debug.DrawRay(contact.point, contact.normal, Color.red);
}
}
void OnCollisionExit(Collision collision)
{
Debug.Log("OnCollisionExit");
isColliding = false;
}
void OnTriggerEnter(Collider other)
{
Debug.Log("OnTriggerEnter");
}
void OnTriggerExit(Collider other)
{
Debug.Log("OnTriggerExit");
}
void Update ()
{
moveDirX = 0;
moveDirY = 0;
if (isColliding)
{
sprite.color = Color.red;
}
else
{
sprite.color = Color.white;
}
// Left
if (Input.GetKey(KeyCode.A))
{
moveDirX = -1;
// Up-Left
if (Input.GetKey(KeyCode.W))
{
moveDirY = 1;
PlayIfNotPlaying("Up");
}
// Down-Left
else if (Input.GetKey(KeyCode.S))
{
moveDirY = -1;
PlayIfNotPlaying("Down");
}
else
{
PlayIfNotPlaying("Left");
}
walking = true;
}
else if (Input.GetKeyUp(KeyCode.A))
{
walking = false;
}
// Right
if (Input.GetKey(KeyCode.D))
{
moveDirX = 1;
// Up-Right
if (Input.GetKey(KeyCode.W))
{
moveDirY = 1;
PlayIfNotPlaying("Up");
}
// Down-Right
else if (Input.GetKey(KeyCode.S))
{
moveDirY = -1;
PlayIfNotPlaying("Down");
}
else
{
PlayIfNotPlaying("Right");
}
walking = true;
}
else if (Input.GetKeyUp(KeyCode.D))
{
walking = false;
}
// Up
if (Input.GetKey(KeyCode.W))
{
moveDirY = 1;
// Up-Right
if (Input.GetKey(KeyCode.D))
{
moveDirX = 1;
}
PlayIfNotPlaying("Up");
walking = true;
}
else if (Input.GetKeyUp(KeyCode.W))
{
walking = false;
}
// Down
if (Input.GetKey(KeyCode.S))
{
moveDirY = -1;
// Down-Right
if (Input.GetKey(KeyCode.D))
{
moveDirX = 1;
}
PlayIfNotPlaying("Down");
walking = true;
}
else if (Input.GetKeyUp(KeyCode.S))
{
walking = false;
}
if (walking)
{
movement = new Vector3(moveDirX, moveDirY, 0f);
movement *= Time.deltaTime * moveSpeed;
transform.Translate(movement.x, movement.y, 0f);
}
else
{
PlayIfNotPlaying("Idle");
}
}
}