Sunday, June 22, 2014

Unity Touch Button Platformer - Move the player with touch controls



Check out the code below the videos



This Unity tutorial will show you how to make a Player move and jump with on-screen touch buttons for a mobile game.

Google+ Community: https://plus.google.com/communities/108584850180626452949
Twitter: https://twitter.com/Devination3D
Facebook: https://www.facebook.com/unity3Dtutorialsbydevin

To connect your device to unity, download the unity remote app and follow these steps: http://answers.unity3d.com/questions/198853/unity-remote-for-android-not-working-solution.html

Time Breakdown:
0:28 - Setting up the player GameObject
2:18 - Starting the PlayerMovement script
4:25 - Move Function
6:42 - Setting up keyboard controls for Movement
7:40 - Explaination of InputManager (skip this section if you're already familiar with it)
8:57 - Jump Function
8:45 - Setting up keyboard controls for Jump
11:00 - GetButton vs GetButtonDown
11:45 - Defining up platform dependant code blocks with #if and #endif
14:25 - Checking if player isGrounded with LineCasting
19:20 - Demonstration of LineCasting
20:08 - Setting up Touch Buttons
21:31 - Setting up the Move Touch Button
26:44 - Setting up the Jump Touch Button
28:05 - Demonstration on Touch Screen Android




Support Further Tutorial Development
Comments?
Check out the videos above to hear the explanation and see the code in action
/*/
* Script by Devin Curry
* www.Devination.com
* www.youtube.com/user/curryboy001
* Please like and subscribe if you found my tutorials helpful :D
* Google+ Community: https://plus.google.com/communities/108584850180626452949
* Twitter: https://twitter.com/Devination3D
* Facebook Page: https://www.facebook.com/unity3Dtutorialsbydevin
/*/
using UnityEngine;
using System.Collections;

public class PlayerMovement : MonoBehaviour 
{
 public float speed = 500f, jumpHeight = 500f;
 Transform myTrans;
 Rigidbody2D myBody;
 Vector2 movement;//used as temp holder variable before applying to velocity
 bool isGrounded = true;


 void Start () 
 {
  myTrans = this.transform;
  myBody = this.rigidbody2D;
 }

 void Update () 
 {
  //Check if the player is grounded or not
  isGrounded = Physics2D.Linecast(myTrans.position,
                                  GameObject.Find(this.name+"/tag_ground").transform.position,
                                  LayerMask.NameToLayer("Player"));

  //Just for visualization, not needed for gameplay
  Debug.DrawLine (myTrans.position,
                  GameObject.Find(this.name+"/tag_ground").transform.position,
                  Color.red);
  
  
  //Works for keyboards and joysticks
  #if !UNITY_ANDROID && !UNITY_IPHONE && !UNITY_BLACKBERRY && !UNITY_WINRT
  Move (Input.GetAxisRaw("Horizontal"));
  if (Input.GetButtonDown ("Jump"))
   Jump ();
  #endif
 }
 //
 //Separate Move and Jump so they can be called externally by TouchButtons
 //
 public void Move(float horizontal_input)
 {
  movement = myBody.velocity;

  if(isGrounded)//we can only move left and right if on the ground
   movement.x = horizontal_input * speed * Time.deltaTime;

  //Apply the movement to the player
  myBody.velocity = movement;
 }
 public void Jump()//we can only jump if on the ground
 {
  if(isGrounded)
   myBody.velocity += jumpHeight * Vector2.up * Time.deltaTime;
 }
}
The Move Buttons:
using UnityEngine;
using System.Collections;

public class MoveButton : TouchLogicV2 
{
 [Range(-1,1)]
 public int moveDir = 1;//1=right;-1=left
 PlayerMovement player;

 void Start()
 {
  player = FindObjectOfType();//This will find our player script, as long as there is only 1 GameObject with "PlayerMovement" on it
 }

 public override void OnTouchBegan()
 {
  //watch this touch for when it ends anywhere so we can slow down the player
  touch2Watch = currTouch;
 }

 public override void OnTouchMoved()
 {
  player.Move (moveDir);
 }
 public override void OnTouchStayed()
 {
  player.Move (moveDir);
 }
 public override void OnTouchEndedAnywhere()
 {
  //run this check so other touches ending don't cause player to slow down
  if(currTouch == touch2Watch)
   player.Move(0);//do avoid annoying drift after letting go of button
 }
}
The Jump Button:
using UnityEngine;
using System.Collections;

public class JumpButton : TouchLogicV2 
{
 PlayerMovement player;
 void Start()
 {
  player = FindObjectOfType();
 }
 
 public override void OnTouchBegan()
 {
  player.Jump ();
 }
}

Wednesday, January 29, 2014

Unity GUI Tutorial - Scale GUI to the right size for every resolution


Check out the code below the videos



This Unity Tutorial will show you how to make your GUI automatically scale to the right size for every screen resolution and aspect ratio.

Google+ Community: https://plus.google.com/communities/108584850180626452949
Twitter: https://twitter.com/Devination3D
Facebook: https://www.facebook.com/unity3Dtutorialsbydevin

To connect your device to unity, download the unity remote app and follow these steps: http://answers.unity3d.com/questions/198853/unity-remote-for-android-not-working-solution.html

Time Breakdown:
1:20 - Overview of different aspect ratios for mobile and desktop
2:00 - Demonstration and explaination of why Pixel Inset values are not good for scalability
3:10 - Explaination of how Pixel Inset values work
5:00 - Use Transform Position and Scale values instead!
7:30 - GUITexture anchor points are in the center by default
7:50 - How to change the anchor point of a GUITexture (useful for health bars and such)
9:45 - Demonstration of why you can't get perfect squares and circles without code
10:10 - Using a script to make a perfect square GUITexture
11:39 - Explaination of how the script works
15:20 - Outro Thanks for watching :D




Support Further Tutorial Development
Comments?
Check out the videos above to hear the explanation and see the code in action
/*/
* Script by Devin Curry
* www.Devination.com
* www.youtube.com/user/curryboy001
* Please like and subscribe if you found my tutorials helpful :D
* Google+ Community: https://plus.google.com/communities/108584850180626452949
* Twitter: https://twitter.com/Devination3D
* Facebook Page: https://www.facebook.com/unity3Dtutorialsbydevin
*
* Attach this script to a GUITexture or GUIText to fix its scale to the aspect ratio of the current screen
* Change the values of scaleOnRatio1 (units are in % of screenspace if the screen were square, 0f = 0%, 1f = 100%) to change the desired ratio of the GUI
* The ratio is width-based so scaleOnRatio1.x will stay the same, scaleOnRatio1.y will based on the screen ratio
*
* The most common aspect ratio for COMPUTERS is 16:9 followed by 16:10
* Possible aspect ratios for MOBILE are:
* 4:3
* 3:2
* 16:10
* 5:3
* 16:9
/*/
using UnityEngine;
using System.Collections;

public class GUIAspectRatioScale : MonoBehaviour 
{
 public Vector2 scaleOnRatio1 = new Vector2(0.1f, 0.1f);
 private Transform myTrans;
 private float widthHeightRatio;

 void Start () 
 {
  myTrans = transform;
  SetScale();
 }
 //call on an event that tells if the aspect ratio changed
 void SetScale()
 {
  //find the aspect ratio
  widthHeightRatio = (float)Screen.width/Screen.height;
  
  //Apply the scale. We only calculate y since our aspect ratio is x (width) authoritative: width/height (x/y)
  myTrans.localScale = new Vector3 (scaleOnRatio1.x, widthHeightRatio * scaleOnRatio1.y, 1);
 }
}

Tuesday, January 21, 2014

Unity TouchLogic3D Tutorial - Improved Touch Input


Check out the code below the videos



In this Unity tutorial we will separate and improve the 3D portion of our TouchLogic script (original here) making it more optimized for better performance. I will rewrite and better explain a few things to solve any issues you may have had with the original.

Time Breakdown:
0:10 - Overview of how and what we will be doing
1:00 - How to make this script work for 2D colliders
1:28 - Why are we separating TouchLogic3D and TouchLogicV2?
2:25 - Creating the ITouchable3D interface
4:45 - Implementing our interface in our script for touchable objects
8:00 - Creating our TouchLogic3D script
10:00 - Checking what the raycast hit
12:28 - Checking if what we hit is actually touchable
15:12 - Demonstrating that our script recognizes what is touchable and what is not
16:23 - Removing SendMessage and calling functions directly
19:24 - Finished with the touch functions, moving on to the Anywhere functions
23:15 - Demonstrating why we need a touch2Watch variable
25:30 - Outro, thanks for watching :D




Support Further Tutorial Development
Comments?
Check out the videos above to hear the explanation and see the code in action
/*/
* Script by Devin Curry
* www.Devination.com
* www.youtube.com/user/curryboy001
* Please like and subscribe if you found my tutorials helpful :D
* Google+ Community: https://plus.google.com/communities/108584850180626452949
* Twitter: https://twitter.com/Devination3D
* Facebook Page: https://www.facebook.com/unity3Dtutorialsbydevin
/*/
using UnityEngine;
using System.Collections;

public class TouchLogic3D : MonoBehaviour 
{
 public static int currTouch = 0;//so other scripts can know what touch is currently on screen
 private int touch2Watch = 64;
 private Ray ray;//this will be the ray that we cast from our touch into the scene
 private RaycastHit rayHitInfo = new RaycastHit();//return the info of the object that was hit by the ray
 private ITouchable3D touchedObject = null;
 
 void Update () 
 {
  for(int i = 0; i < Input.touchCount; i++)
  {
   currTouch = i;
   ray = Camera.main.ScreenPointToRay(Input.GetTouch(i).position);//creates ray from screen point position
   //if the ray hit something, only if it hit something
   if(Physics.Raycast(ray, out rayHitInfo))
   {
    //if the thing that was hit implements ITouchable3D
    touchedObject = rayHitInfo.transform.GetComponent(typeof(ITouchable3D)) as ITouchable3D;
    //Debug.Log (touchedObject);
    //If the ray hit something and it implements ITouchable3D
    if (touchedObject != null)
    {
     switch(Input.GetTouch(i).phase)
     {
     case TouchPhase.Began:
      touchedObject.OnTouchBegan();
      touch2Watch = currTouch;
      break;
     case TouchPhase.Ended:
      touchedObject.OnTouchEnded();
      break;
     case TouchPhase.Moved:
      touchedObject.OnTouchMoved();
      break;
     case TouchPhase.Stationary:
      touchedObject.OnTouchStayed();
      break;
     }
    }
   }
   //On Anywhere
   else if (touchedObject != null && touch2Watch == currTouch)
   {
    switch(Input.GetTouch(i).phase)
    {
    case TouchPhase.Ended:
     touchedObject.OnTouchEndedAnywhere();
     touchedObject = null;
     break;
    case TouchPhase.Moved:
     touchedObject.OnTouchMovedAnywhere();
     break;
    case TouchPhase.Stationary:
     touchedObject.OnTouchStayedAnywhere();
     break;
    }
   }
  }
 }
}
And the interface:
/*/
* Script by Devin Curry
* www.Devination.com
* www.youtube.com/user/curryboy001
* Please like and subscribe if you found my tutorials helpful :D
* Google+ Community: https://plus.google.com/communities/108584850180626452949
* Twitter: https://twitter.com/Devination3D
* Facebook Page: https://www.facebook.com/unity3Dtutorialsbydevin
/*/
public interface ITouchable3D 
{
//Remove functions you know you arent going to use
// void OnNoTouches();
 void OnTouchBegan();
 void OnTouchEnded();
 void OnTouchMoved();
 void OnTouchStayed();
// void OnTouchBeganAnywhere();
 void OnTouchEndedAnywhere();
 void OnTouchMovedAnywhere();
 void OnTouchStayedAnywhere();
}