效果预览

[Unity2D]2D Mobile Joystick_IT

操作步骤

1、下载素材 http://pan.bai du.com/s/1gdkQz8v

2、新建一个GUITexture(Joystick)及一个Sprite(Nyan)

    [Unity2D]2D Mobile Joystick_IT_02  [Unity2D]2D Mobile Joystick_IT_03

3、添加背景及Platform(添加BoxCollider2D)

[Unity2D]2D Mobile Joystick_IT_04

4、创建C#脚本 JoystickInput.cs

JoystickInput.cs

using UnityEngine;
using System.Collections;

public class JoystickInput : MonoBehaviour
{
    public Joystick joystick;// Reference to joystick prefab
    public float speed = 10; // Movement speed
    public bool useAxisInput = true;// Use Input Axis or Joystick
    private float h = 0, v = 0;// Horizontal and Vertical values


    // Update is called once per frame
    void Update()
    {
        if (!useAxisInput)
        {
            h = joystick.position.x;
            v = joystick.position.y;
        }
        else
        {
            h = Input.GetAxis("Horizontal");
            v = Input.GetAxis("Vertical");
        }
        // Apply horizontal velocity
        if (Mathf.Abs(h) > 0)
        {
            rigidbody2D.velocity = new Vector2(h * speed, rigidbody2D.velocity.y);
        }

        // Apply vertical velocity
        if (Mathf.Abs(v) > 0)
        {
            rigidbody2D.velocity = new Vector2(rigidbody2D.velocity.x, v * speed);
        }
    }
}

工程文件

源文件下载(Unity 4.3.4) http://pan.baidu.com/s/1kT7IP5H

注意事项

 如果Unity自带的 Joystick.js 会报引用异常,找不到Joystick,所以使用Joystick.cs 附地址:http://wiki.unity3d.com/index.php?title=Joystick