1、打开unity软件,点击Window——点击Asset Store——点击Search online
进入资源网站后,搜索Joystick Pack并下载,然后点击在unity中打开,然后点击import将资源导入。
2、在unity中新建一个平面(Plane)和小球(Sphere)以及Canvas并将Joystick pack资源包中Fixed Joysticl放到Canvas里,还新建一个Button按钮,在其属性里数值及样式更改如图,也放置在Canvas下。并调整好位置。如图所示:
3、点击Canvas,将其属性改为如图所示:
4、新建两个代码,分别命名JoyButton、Sphere Jump。
JoyButton代码内容如图:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class JoyButton : MonoBehaviour, IPointerDownHandler,IPointerUpHandler
{
[HideInInspector]
public bool pressed;
public void OnPointerDown(PointerEventData eventData)
{
pressed = true;
}
public void OnPointerUp(PointerEventData eventData)
{
pressed = false;
}
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
Sphere Jump代码内容如图:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SphereJump : MonoBehaviour
{
protected Joystick joustick;
protected JoyButton joyButton;
public bool jump;
void Start()
{
joustick= FindObjectOfType<Joystick>();
joyButton = FindObjectOfType<JoyButton>();
}
// Update is called once per frame
void Update()
{
var rigidbody = GetComponent<Rigidbody>();
rigidbody.velocity = new Vector3(joustick.Horizontal * 10f,
rigidbody.velocity.y, joustick.Vertical * 10f);
if(!jump && joyButton.pressed)
{
jump = true;
rigidbody.velocity += Vector3.up * 10f;
}
if (jump && !joyButton.pressed)
{
jump = false;
}
}
}
5、点击小球(Sphere)把代码SphereJump拖拽到属性里面,再添加一个Rigidbody属性。如图:
6、点击Button,把代码JoyButton拖拽到属性里。
这样就完成了!就可以运行效果了。
|